feat(menubar): 拆分紧凑双页面板并按页采样

This commit is contained in:
2026-11-08 10:42:55 +08:00
parent ac8b4a7e6a
commit 41dcc497b5
36 changed files with 465 additions and 288 deletions
+3
View File
@@ -47,6 +47,9 @@ import AppKit
openSettingsAction = { settings.environment.openSettings() }
configureMainMenu()
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) },
pageChanged: { [metrics] page in
metrics.setDetailDemand(processes: page == .processes, slowMetrics: page == .overview)
},
menuTitle: { [language] key in
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
+13 -1
View File
@@ -35,6 +35,18 @@ nonisolated struct ProcessEnergySnapshot: Sendable {
let candidates: Int
let readable: Int
let measured: Int
let rows: [ProcessEnergyUsage] // Only the top three; no CPU prefilter.
let rows: [ProcessEnergyUsage] // All valid measurements; no CPU prefilter.
let state: State
}
nonisolated extension ProcessSnapshot {
func withEnergy(_ energy: ProcessEnergySnapshot?) -> ProcessSnapshot {
let values = Dictionary((energy?.rows ?? []).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
return ProcessSnapshot(date: date, enumerated: enumerated, readable: readable, rows: rows.map { process in
var row = process
row.cpuPower = values[process.id]?.watts
row.powerWindow = values[process.id]?.seconds
return row
}, failed: failed)
}
}
+6
View File
@@ -14,6 +14,12 @@ nonisolated struct ProcessMetrics: Identifiable, Sendable {
let footprintBytes: UInt64? // Physical footprint; never RSS.
let threads: Int?
let restricted: Bool
var cpuPower: Double? = nil // Average attributed CPU power, watts; not Energy Impact.
var powerWindow: TimeInterval? = nil
var formattedPower: String {
guard let cpuPower, cpuPower.isFinite, cpuPower >= 0 else { return "--" }
return cpuPower >= 1 ? String(format: "%.2f W", cpuPower) : String(format: "%.1f mW", cpuPower * 1000)
}
}
nonisolated struct ProcessSnapshot: Sendable {
@@ -29,15 +29,12 @@ nonisolated struct ProcessEnergyMonitor: Sendable {
if let (power, seconds) = Self.watts(current: reading, previous: previous[reading.id], maximumInterval: maximumInterval) {
measured += 1
let usage = ProcessEnergyUsage(process: process, watts: power, seconds: seconds)
let index = usages.firstIndex {
$0.watts < power || ($0.watts == power && $0.id.pid > process.id.pid)
} ?? usages.endIndex
usages.insert(usage, at: index)
if usages.count > 3 { usages.removeLast() }
usages.append(usage)
}
}
}
previous = next // Failed / missing readings invalidate the old baseline.
usages.sort { $0.watts == $1.watts ? $0.id.pid < $1.id.pid : $0.watts > $1.watts }
let state: ProcessEnergySnapshot.State
if capability == .unsupported { state = .unsupported }
else if capability == .unavailable || processes.failed || (capability == .verifiedCPU && next.isEmpty) { state = .unavailable }
+17 -6
View File
@@ -11,9 +11,12 @@ final class MetricsStore {
private(set) var isSystemSleeping = false
private(set) var isDisplaySleeping = false
private(set) var isPanelVisible = false
private(set) var processUpdatesRequested = false
private(set) var slowMetricsRequested = true
let sampling: SamplingPreferences
private let energyEnabled: Bool
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
private var processDemand: Bool { panelDemand && processUpdatesRequested }
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
// Permit timer coalescing without changing the requested cadence or delta timestamps.
@@ -72,25 +75,25 @@ final class MetricsStore {
while !Task.isCancelled {
let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample(includeProcesses: self?.panelDemand == true,
includeSlowMetrics: self?.panelDemand == true,
var next = await sampler.sample(includeProcesses: self?.processDemand == true,
includeSlowMetrics: self?.panelDemand == true && self?.slowMetricsRequested == true,
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
self.processDemand, !self.isPaused, !self.isSystemSleeping else { return }
if self.processSnapshot.map({ $0.date > processes.date }) != true { self.processSnapshot = processes }
}
}, energyUpdate: { [weak self] energy in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
self.processDemand, !self.isPaused, !self.isSystemSleeping else { return }
self.energy = energy
SamplingDiagnostics.recordEnergy(energy)
}
})
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
if self?.panelDemand != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
if self?.processDemand != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
else if let completed = self?.processSnapshot, completed.date >= next.date {
// A fast detached process result may reach MainActor before this quick snapshot.
next.processes = completed
@@ -143,10 +146,18 @@ final class MetricsStore {
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
}
/// The caller supplies data needs, without introducing UI types into Core.
func setDetailDemand(processes: Bool, slowMetrics: Bool) {
guard processUpdatesRequested != processes || slowMetricsRequested != slowMetrics else { return }
processUpdatesRequested = processes
slowMetricsRequested = slowMetrics
updateDemand(reset: false, sampleImmediately: panelDemand)
}
private func updateDemand(reset: Bool, sampleImmediately: Bool = true) {
visibilityGeneration += 1
let revision = visibilityGeneration
let active = panelDemand && !isPaused && !isSystemSleeping
let active = processDemand && !isPaused && !isSystemSleeping
if !active { processSnapshot = nil }
energy = nil
Task { await sampler.setProcessVisible(active, revision: revision) }
+8 -16
View File
@@ -42,11 +42,6 @@ struct CPUCoreGrid: 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 {
@@ -63,7 +58,7 @@ struct CPUCoreGrid: View {
.lineLimit(1).minimumScaleFactor(0.6)
CPUCoreGridLayout {
ForEach(groups[group], id: \.self) { index in
ring(index: index, maximumDiameter: min(20, diameter))
core(index: index)
}
}
}.frame(width: widths[group], alignment: .topLeading)
@@ -82,20 +77,17 @@ struct CPUCoreGrid: View {
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 {
private func core(index: Int) -> 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 {
NativeMetricRing(value: value, color: color(kind), lineWidth: 2, trackOpacity: 0.16, inset: 1)
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)
return VStack(spacing: 3) {
Text(verbatim: "\(Int((value * 100).rounded()))")
.font(.system(size: 8, weight: .medium)).monospacedDigit().lineLimit(1)
MetricProgressBar(value: value, color: color(kind)).frame(height: 3)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(value))"))
.accessibilityElement(children: .ignore)
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
}
@@ -1,64 +0,0 @@
import SwiftUI
/// A separate observation scope: energy completion does not replace the resource snapshot.
struct EnergyProcessSection: View {
let metrics: MetricsStore
private var snapshot: ProcessEnergySnapshot? { metrics.energy }
private var rows: [ProcessEnergyUsage] { snapshot?.rows ?? [] }
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text("energy.cpuProcesses").font(PanelStyle.section)
if snapshot?.state == .partial {
Text("energy.partial").font(.system(size: 8)).foregroundStyle(.secondary)
.help(Text("energy.coverage \(snapshot?.measured ?? 0) \(snapshot?.candidates ?? 0)"))
}
Spacer()
Text("energy.averagePower").foregroundStyle(.secondary)
}.font(PanelStyle.label)
if rows.isEmpty {
Text(statusKey).foregroundStyle(.secondary).font(PanelStyle.label)
} else {
ForEach(rows) { usage in
EnergyProcessListRow(usage: usage, maximum: rows.first?.watts ?? 0)
}
}
}
.help(Text("energy.scopeHelp"))
}
private var statusKey: LocalizedStringKey {
switch snapshot?.state {
case .unsupported: "energy.unsupported"
case .unavailable: "energy.unavailable"
default: "energy.waiting"
}
}
}
private struct EnergyProcessListRow: View {
let usage: ProcessEnergyUsage
let maximum: Double
private var progress: Double { maximum > 0 ? min(1, max(0, usage.watts / maximum)) : 0 }
var body: some View {
HStack(spacing: 5) {
ProcessIcon(process: usage.process)
Text(verbatim: usage.process.name).lineLimit(1).truncationMode(.middle)
.frame(width: 66, alignment: .leading)
GeometryReader { proxy in
Capsule().fill(.primary.opacity(0.07))
.overlay(alignment: .leading) {
Capsule().fill(Color("MetricCPU"))
.frame(width: proxy.size.width * progress, height: 4).clipped()
}.clipShape(Capsule())
}.frame(height: 4)
Text(verbatim: usage.formattedPower)
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
.monospacedDigit().frame(width: 57, alignment: .trailing)
}
.font(PanelStyle.label).frame(height: 16)
.help(Text("energy.window \(usage.seconds.formatted(.number.precision(.fractionLength(1))))"))
.accessibilityElement(children: .combine)
}
}
@@ -2,10 +2,14 @@ import AppKit
import SwiftUI
import Observation
enum PanelPage: Hashable { case overview, processes }
@MainActor @Observable final class PanelPresentation {
fileprivate(set) var isOpen = false
var isPinned = false { didSet { onPinChange?(isPinned) } }
var page: PanelPage = .overview { didSet { if oldValue != page { onPageChange?(page) } } }
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
@ObservationIgnored var onPageChange: ((PanelPage) -> Void)?
}
/// Owns only status-item/window behavior. Sampling and settings are injected by App.
@@ -28,6 +32,7 @@ import Observation
private var isHiding = false
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
pageChanged: @escaping (PanelPage) -> Void = { _ in },
menuTitle: @escaping (String) -> String = { $0 },
openSettings: @escaping () -> Void = {},
@ViewBuilder content: @escaping (PanelPresentation) -> Content) {
@@ -51,6 +56,7 @@ import Observation
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.dismiss = { [weak self] in self?.hide() }
presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal }
presentation.onPageChange = pageChanged
if installStatusItem {
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
item.button?.image = NSImage(named: "BrandMark")
@@ -116,6 +122,7 @@ import Observation
func show() {
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
place()
presentation.page = .overview
presentation.isOpen = true
panel.contentView = content(presentation)
panel.level = presentation.isPinned ? .floating : .normal
@@ -42,33 +42,10 @@ extension MenuPanelView {
} else {
Text("metric.waiting").foregroundStyle(.secondary)
}
Spacer(minLength: 0)
CardSeparator()
HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary)
Spacer(minLength: 3)
MetricText(
value: snapshot.load.first.map { "\(MetricFormat.decimal($0)) / \(snapshot.cpu?.cores.count ?? 0)" } ?? "--")
}
MetricProgressBar(
value: (snapshot.load.first ?? 0) / Double(max(1, snapshot.cpu?.cores.count ?? 0)), color: Color("MetricCPU")
)
.frame(height: 5).accessibilityHidden(true)
}.frame(maxWidth: .infinity)
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 25)
VStack(alignment: .leading, spacing: 3) {
Text("panel.uptime").foregroundStyle(.secondary)
MetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
.fontWeight(.medium)
}
}.font(PanelStyle.label).lineLimit(1)
}
}
var gpuCard: some View {
let summary = GPUUtilizationSummary(samples: samples)
return ResourceCard(
title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" },
@@ -81,15 +58,6 @@ extension MenuPanelView {
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
CardSeparator()
gpuActivity("gpu.rendererActivity", value: snapshot.gpu?.renderer, color: Color("MetricCPU"))
gpuActivity("gpu.tilerActivity", value: snapshot.gpu?.tiler, color: Color("SeriesSystem"))
CardSeparator()
Spacer(minLength: 0)
GPUStatisticsView(
inUse: snapshot.gpu?.inUseMemory, allocated: snapshot.gpu?.allocatedMemory,
average: summary.average, peak: summary.peak
)
Spacer(minLength: 0)
let fans = displayedFans
if !fans.isEmpty {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) {
@@ -105,13 +73,6 @@ extension MenuPanelView {
}
}
func gpuActivity(_ title: LocalizedStringKey, value: Double?, color: Color) -> some View {
HStack(spacing: 8) {
Text(title).font(PanelStyle.label).frame(width: 100, alignment: .leading)
MetricProgressBar(value: value ?? 0, color: color).frame(height: 5)
MetricText(value: MetricFormat.percent(value)).font(PanelStyle.value).frame(width: 30, alignment: .trailing)
}.font(PanelStyle.label)
}
var memoryCard: some View {
ResourceCard(
title: "metric.memory", symbol: "memorychip", color: Color("MemoryApplication"),
@@ -235,12 +196,6 @@ extension MenuPanelView {
.font(PanelStyle.label)
.lineLimit(1)
.frame(height: 32)
Spacer(minLength: 0)
CardSeparator()
EnergyProcessSection(metrics: metrics)
// Reserve the header and all three rows before process sampling completes.
.frame(height: 74, alignment: .top)
.lineLimit(1)
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
+61 -35
View File
@@ -13,6 +13,7 @@ struct MenuPanelView: View {
@State var selectedInterface = ""
@State var publicIPAddress: String?
@State var showVolumes = false
@State private var processState = ProcessTableState()
var snapshot: MetricsSnapshot { metrics.snapshot }
var samples: [TrendSample] { metrics.history.samples }
@@ -47,16 +48,19 @@ struct MenuPanelView: View {
var body: some View {
VStack(spacing: PanelStyle.gap) {
if PanelResourceAudit.omitted != "header" { header }
if PanelLayout.needsResourceScroll(size: panelSize, rows: rowHeights) {
ScrollView { resourceRows }
.frame(maxHeight: PanelLayout.resourceHeight(rows: rowHeights))
} else {
resourceRows
}
if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
PanelProcessSection(metrics: metrics, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(minHeight: 170)
if presentation.page == .overview {
if PanelLayout.needsResourceScroll(size: panelSize, rows: rowHeights) {
ScrollView { resourceRows }
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
resourceRows
.frame(maxHeight: .infinity, alignment: .top)
}
} else if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
PanelProcessSection(metrics: metrics, state: processState, wide: panelSize.width >= 800)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
footer
}
.padding(PanelStyle.padding)
.frame(width: panelSize.width, height: panelSize.height)
@@ -101,41 +105,62 @@ struct MenuPanelView: View {
} else {
switch index {
case 0: cpuCard
case 1: gpuCard
case 2: batteryCard
case 3: memoryCard
case 4: diskCard
case 1: batteryCard
case 2: gpuCard
case 3: diskCard
case 4: memoryCard
case 5: networkCard
default: EmptyView()
}
}
}
private var brand: some View {
HStack(spacing: 6) {
Image("BrandMark").renderingMode(.template).resizable().scaledToFit()
.frame(width: 22, height: 22)
Text("Kymo").font(.system(size: 17, weight: .semibold))
}
}
private var pagePicker: some View {
Picker("panel.page", selection: Binding(get: { presentation.page }, set: { presentation.page = $0 })) {
Text("panel.overview").tag(PanelPage.overview)
Text("panel.processes").tag(PanelPage.processes)
}
.pickerStyle(.segmented).labelsHidden().frame(width: 164)
.accessibilityIdentifier("panel.tabs")
}
private var header: some View {
HStack(spacing: 10) {
Image("BrandMark")
.renderingMode(.template)
.resizable()
.scaledToFit()
.frame(width: 24, height: 24)
HStack(alignment: .firstTextBaseline, spacing: 2) {
Text("Kymo").font(.system(size: 18, weight: .semibold))
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")")
.font(.system(size: 8, weight: .medium))
.foregroundStyle(.secondary)
.baselineOffset(7)
VStack(spacing: 4) {
HStack(spacing: 8) {
brand
Spacer(minLength: 8)
controls
}
if panelSize.width >= 900 {
Rectangle()
.fill(.secondary.opacity(0.32))
.frame(width: 1, height: 16)
.accessibilityHidden(true)
Text(verbatim: HardwareIdentity.displayName)
.font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
.frame(height: 32)
.overlay {
if panelSize.width >= 840 { pagePicker }
}
if panelSize.width < 840 { pagePicker.frame(maxWidth: .infinity).frame(height: 28) }
}
.frame(height: PanelLayout.headerHeight(width: panelSize.width))
.padding(.horizontal, 4)
}
private var footer: some View {
HStack {
Text(verbatim: HardwareIdentity.displayName)
.lineLimit(1).truncationMode(.middle)
Spacer(minLength: 8)
controls
}.padding(.horizontal, 4)
HStack(spacing: 4) {
Text("panel.uptime")
MetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
}
}
.font(PanelStyle.label).foregroundStyle(.secondary)
.frame(height: 18).padding(.horizontal, 4)
}
private var controls: some View {
@@ -217,6 +242,7 @@ private struct PanelControlButtonBody<Content: View>: View {
/// Keep process publications out of the resource-card observation scope.
private struct PanelProcessSection: View {
let metrics: MetricsStore
let state: ProcessTableState
let wide: Bool
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, wide: wide) }
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, energy: metrics.energy, state: state, wide: wide) }
}
+14 -5
View File
@@ -25,7 +25,7 @@ import SwiftUI
table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear
table.allowsMultipleSelection = false; table.allowsEmptySelection = true
table.columnAutoresizingStyle = .sequentialColumnAutoresizingStyle
for (key, width) in [("pid", 48.0), ("name", 140), ("path", 400), ("cpu", 65), ("memory", 85), ("threads", 65)] {
for (key, width) in [("pid", 48.0), ("name", 140), ("path", 250), ("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
@@ -148,9 +148,18 @@ import SwiftUI
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
default: text = process.threads.map(String.init) ?? "--"
}
if cell.textField?.stringValue != text { cell.textField?.stringValue = text }
if key == "power" {
let help = AppLocalization.string("energy.scopeHelp", locale: parent.locale)
let window = process.powerWindow.map {
String(format: AppLocalization.string("energy.window %@", locale: parent.locale), String(format: "%.1f", $0))
}
let tooltip = window.map { help + "\n" + $0 } ?? help
if cell.toolTip != tooltip { cell.toolTip = tooltip }
}
if key == "name" {
let image = PanelResourceAudit.omitted == "icons" ? nil : process.path.flatMap { ProcessIconCache.shared.image(for: $0) }
let desired = image ?? Self.placeholder
@@ -203,10 +212,10 @@ import SwiftUI
NSPasteboard.general.clearContents(); NSPasteboard.general.setString(value, forType: .string)
}
private static func name(_ key: ProcessSort.Key) -> String {
switch key { case .pid: "pid"; case .name: "name"; case .path: "path"; case .cpu: "cpu"; case .memory: "memory"; case .threads: "threads" }
switch key { case .pid: "pid"; case .name: "name"; case .path: "path"; case .cpu: "cpu"; case .memory: "memory"; case .threads: "threads"; case .power: "power" }
}
private static func key(_ name: String) -> ProcessSort.Key? {
switch name { case "pid": .pid; case "name": .name; case "path": .path; case "cpu": .cpu; case "memory": .memory; case "threads": .threads; default: nil }
switch name { case "pid": .pid; case "name": .name; case "path": .path; case "cpu": .cpu; case "memory": .memory; case "threads": .threads; case "power": .power; default: nil }
}
}
@@ -216,8 +225,8 @@ import SwiftUI
self.key = key
super.init(frame: .zero)
let text = NSTextField(labelWithString: "")
text.font = ["pid", "cpu", "memory", "threads"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11)
text.alignment = ["cpu", "memory", "threads"].contains(key) ? .right : .left
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
addSubview(text); textField = text
+11 -10
View File
@@ -2,18 +2,19 @@ import Foundation
import CoreGraphics
nonisolated enum PanelLayout {
static let baseCardHeight: CGFloat = 280
static func columns(width: CGFloat) -> Int { width >= 1160 ? 3 : width >= 900 ? 2 : 1 }
static let baseCardHeight: CGFloat = 204
static func headerHeight(width: CGFloat) -> CGFloat { width >= 840 ? 32 : 64 }
static func columns(width: CGFloat) -> Int { width >= 680 ? 2 : 1 }
static func cardWidth(size: CGSize) -> CGFloat {
let count = columns(width: size.width)
return max(0, (size.width - 20 - CGFloat(count - 1) * 8) / CGFloat(count))
}
/// Heights are assigned by physical row, including the battery/memory pair at two columns.
/// Physical order: CPU/battery, GPU/storage, memory/network.
static func rowHeights(columns: Int, coreRows: Int, fanCount: Int) -> [CGFloat] {
let cpu = baseCardHeight + CGFloat(max(0, coreRows - 2)) * 26
let cpu: CGFloat = 220 + CGFloat(max(0, coreRows - 2)) * 26
let gpu = baseCardHeight + CGFloat(max(0, (fanCount + 1) / 2 - 1)) * 26
let heights = [cpu, gpu, baseCardHeight, baseCardHeight, baseCardHeight, baseCardHeight]
let count = max(1, min(3, columns))
let heights = [cpu, baseCardHeight, gpu, baseCardHeight, 260, 260]
let count = max(1, min(2, columns))
return stride(from: 0, to: heights.count, by: count).map {
heights[$0..<min($0 + count, heights.count)].max() ?? baseCardHeight
}
@@ -22,13 +23,13 @@ nonisolated enum PanelLayout {
rows.reduce(0, +) + CGFloat(max(0, rows.count - 1)) * 8
}
static func needsResourceScroll(size: CGSize, rows: [CGFloat]) -> Bool {
// Outer padding, toolbar budget, two gaps, and the minimum process area.
resourceHeight(rows: rows) > size.height - 20 - 40 - 16 - 170
// Outer padding, common toolbar/footer, and two gaps. Process page is separate.
resourceHeight(rows: rows) > size.height - 20 - headerHeight(width: size.width) - 18 - 16
}
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))))
CGSize(width: max(1, min(960, visible.width - 32 - max(0, chrome.width))),
height: max(1, min(800, visible.height - 32 - max(0, chrome.height))))
}
static func centeredFrame(_ frame: CGRect, visible: CGRect) -> CGRect {
var result = constrainedFrame(frame, visible: visible)
+22 -4
View File
@@ -38,24 +38,42 @@ import AppKit
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
controller.presentation.isPinned = true
if ProcessInfo.processInfo.environment["KYMO_AUDIT_INTERACTIVE"] == "1" {
controller.show()
if let value = ProcessInfo.processInfo.environment["KYMO_AUDIT_SIZE"] {
let parts = value.split(separator: "x").compactMap { Double($0) }
if parts.count == 2, parts.allSatisfy({ $0.isFinite }), parts[0] >= 480, parts[1] >= 360 {
controller.panel.setContentSize(CGSize(width: min(parts[0], controller.panel.frame.width),
height: min(parts[1], controller.panel.frame.height)))
}
}
mark("interactive")
return
}
let quick = ProcessInfo.processInfo.environment["KYMO_AUDIT_QUICK"] == "1"
mark("cold")
await wait(10)
await wait(quick ? 3 : 10)
mark("hidden10")
for cycle in 1...3 {
controller.show()
if ProcessInfo.processInfo.environment["KYMO_AUDIT_PAGE"] == "processes" { controller.presentation.page = .processes }
mark("open\(cycle).0")
await wait(1); mark("open\(cycle).1")
await wait(9); mark("open\(cycle).10")
await wait(20); mark("open\(cycle).30")
if cycle == 1 {
if cycle == 1 && !quick {
metrics.togglePause(); mark("paused.0")
await wait(10); mark("paused.10")
metrics.togglePause(); mark("resumed")
}
controller.hide()
await wait(1); mark("closed\(cycle).1")
await wait(9); mark("closed\(cycle).10")
await wait(20); mark("closed\(cycle).30")
if quick {
await wait(4); mark("closed\(cycle).5")
} else {
await wait(9); mark("closed\(cycle).10")
await wait(20); mark("closed\(cycle).30")
}
}
controller.shutdown()
mark("complete")
@@ -32,7 +32,9 @@ struct PanelWindowObserver: NSViewRepresentable {
let frame = (window.screen ?? NSScreen.main)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1000, height: 760)
let chrome = CGSize(width: max(0, window.frame.width - window.contentLayoutRect.width),
height: max(0, window.frame.height - window.contentLayoutRect.height))
let size = PanelLayout.contentSize(visible: frame, chrome: chrome)
let maximum = PanelLayout.contentSize(visible: frame, chrome: chrome)
let size = CGSize(width: min(maximum.width, window.contentLayoutRect.width),
height: min(maximum.height, window.contentLayoutRect.height))
DispatchQueue.main.async { [weak self, weak window] in
guard let self, let window else { return }
self.update(size)
-26
View File
@@ -1,26 +0,0 @@
import AppKit
import SwiftUI
/// Resolves only for visible rows; the task is keyed by process identity and executable path.
struct ProcessIcon: View {
let process: ProcessMetrics
@State private var icon: NSImage?
var body: some View {
Group {
if let icon {
Image(nsImage: icon).resizable().interpolation(.high)
} else {
Image(systemName: "app.dashed").resizable().scaledToFit().padding(2)
}
}
.frame(width: 15, height: 15)
.accessibilityHidden(true)
.task(id: "\(process.id)-\(process.path ?? "")") {
guard PanelResourceAudit.omitted != "icons" else { return }
// Resolve by the sampled executable, avoiding an icon from a reused PID.
guard let path = process.path else { icon = nil; return }
icon = ProcessIconCache.shared.image(for: path)
}
}
}
@@ -27,7 +27,7 @@ nonisolated enum ProcessTableProjection {
/// Missing metrics stay last in either direction. Every newly selected column starts descending.
nonisolated struct ProcessSort: SortComparator, Equatable {
enum Key { case pid, name, path, cpu, memory, threads }
enum Key { case pid, name, path, cpu, memory, threads, power }
let key: Key
var order: SortOrder = .reverse
@@ -46,6 +46,7 @@ nonisolated struct ProcessSort: SortComparator, Equatable {
case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? ""))
case .cpu: return metric(lhs.cpu, rhs.cpu)
case .memory: return metric(lhs.footprintBytes.map { Double($0) }, rhs.footprintBytes.map { Double($0) })
case .power: return metric(lhs.cpuPower, rhs.cpuPower)
case .threads: return metric(lhs.threads.map { Double($0) }, rhs.threads.map { Double($0) })
}
}
+42 -18
View File
@@ -1,22 +1,28 @@
import SwiftUI
import AppKit
import Observation
@MainActor @Observable final class ProcessTableState {
var search = ""
var sortOrder = [ProcessSort(key: .cpu)]
var selected: ProcessIdentity?
var departed: ProcessMetrics?
}
struct ProcessTableView: View {
let snapshot: ProcessSnapshot?
let energy: ProcessEnergySnapshot?
@Bindable var state: ProcessTableState
var wide: Bool = true
@Environment(\.locale) private var locale
@State private var search = ""
@State private var sortOrder = [ProcessSort(key: .cpu)]
@State private var hovering = false
@State private var selected: ProcessIdentity?
@State private var rows: [ProcessMetrics] = []
@State private var departed: ProcessMetrics?
@State private var searchFocused = false
private var held: Bool { hovering || selected != nil || !search.isEmpty }
private var selectedRow: ProcessMetrics? { snapshot?.rows.first { $0.id == selected } }
private var held: Bool { hovering || state.selected != nil || !state.search.isEmpty }
private var selectedRow: ProcessMetrics? { snapshot?.rows.first { $0.id == state.selected } }
private var exitedSelection: ProcessIdentity? {
ProcessTableProjection.exitedSelection(selected, in: snapshot)
ProcessTableProjection.exitedSelection(state.selected, in: snapshot)
}
var body: some View {
@@ -26,33 +32,39 @@ struct ProcessTableView: View {
Spacer(minLength: 0)
searchField.frame(maxWidth: wide ? 220 : 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: $selected, sorting: $sortOrder, locale: locale, onExit: handleExit)
NativeProcessTable(rows: rows, selection: $state.selected, sorting: $state.sortOrder, locale: locale, onExit: handleExit)
.overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } }
if exitedSelection != nil, let departed {
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { selected = nil; self.departed = nil } }
if exitedSelection != nil, let departed = state.departed {
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { state.selected = nil; state.departed = nil } }
}
}
.font(.system(size: 12)).padding(10)
.modifier(CardSurface())
.onAppear { rebuild(retainOrder: false) }
.onChange(of: energy?.date) { _, _ in rebuild(retainOrder: held && !rows.isEmpty) }
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && !rows.isEmpty) }
.onChange(of: search) { _, _ in rebuild(retainOrder: held) }
.onChange(of: sortOrder) { _, _ in rebuild(retainOrder: false) }
.onChange(of: selected) { _, _ in if let row = selectedRow { departed = row } }
.onChange(of: state.search) { _, _ in rebuild(retainOrder: held) }
.onChange(of: state.sortOrder) { _, _ in rebuild(retainOrder: false) }
.onChange(of: state.selected) { _, _ in if let row = selectedRow { state.departed = row } }
.onHover { hovering = $0; if !$0 && !held { rebuild(retainOrder: false) } }
.onChange(of: searchFocused) { _, value in if !value && !held { rebuild(retainOrder: false) } }
.task(id: exitedSelection) {
guard let id = exitedSelection else { return }
do { try await Task.sleep(for: .seconds(3)) } catch { return }
if exitedSelection == id { selected = nil; departed = nil }
if exitedSelection == id { state.selected = nil; state.departed = nil }
}
.onExitCommand(perform: handleExit)
}
private func handleExit() {
if !search.isEmpty { search = "" }
else if selected != nil { selected = nil; departed = nil }
if !state.search.isEmpty { state.search = "" }
else if state.selected != nil { state.selected = nil; state.departed = nil }
else if searchFocused { searchFocused = false }
else { NSApp.keyWindow?.close() }
}
@@ -61,11 +73,23 @@ struct ProcessTableView: View {
.font(PanelStyle.title)
}
private var searchField: some View {
NativeSearchField(text: $search, isFocused: $searchFocused,
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 func rebuild(retainOrder: Bool) {
rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, sorting: sortOrder, order: retainOrder ? rows.map(\.id) : [])
rows = ProcessTableProjection.rows(snapshot?.withEnergy(energy).rows ?? [], query: state.search, sorting: state.sortOrder, order: retainOrder ? rows.map(\.id) : [])
}
}
+4 -10
View File
@@ -4,21 +4,15 @@ struct StorageDetailsView: View {
let disk: DiskMetrics?
let health: DiskHealthMetrics?
let showVolumes: () -> Void
private let color = Color("MetricDisk")
var body: some View {
VStack(alignment: .leading, spacing: 4) {
CardSeparator()
CardSectionHeader(title: "disk.distribution", valueLabel: "disk.utilization",
value: MetricFormat.percent(disk?.usage), color: color)
CapacityBar(values: [Double(disk.map { $0.total - min($0.total, $0.available) } ?? 0), Double(disk?.available ?? 0)],
colors: [color, Color("MemoryAvailable")], total: Double(disk?.total ?? 1))
HStack(spacing: 4) {
CapacityField(title: "disk.used", value: MetricFormat.bytes(disk.map { $0.total - min($0.total, $0.available) }), color: color)
CapacityField(title: "memory.available", value: MetricFormat.bytes(disk?.available), color: Color("MemoryAvailable"))
}
CardSeparator()
HStack(alignment: .top, spacing: 8) {
CardField(title: "memory.available") {
MetricText(value: MetricFormat.bytes(disk?.available))
}
Divider().frame(height: 32)
CardField(title: "disk.remainingLife") {
MetricText(value: MetricFormat.percent(health?.remainingLife))
}
+69 -3
View File
@@ -1,6 +1,72 @@
{
"sourceLanguage" : "en",
"strings" : {
"panel.power" : {
"localizations" : {
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "CPU 功率"
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "CPU power"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "CPU 功率"
}
}
}
},
"panel.overview" : {
"localizations" : {
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "概览"
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Overview"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "概覽"
}
}
}
},
"panel.page" : {
"localizations" : {
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "监控页面"
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Monitoring page"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "監控頁面"
}
}
}
},
"%@\n%@\n%lld / %lld · %lld" : {
"extractionState" : "stale",
"localizations" : {
@@ -1655,19 +1721,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Ranked by system CPU energy counter deltas among measurable processes. Not total app/device power; GPU, display, network and helper processes are not aggregated. Bars are relative to this list."
"value" : "Average power from system CPU energy counter deltas over the measured interval. Not total app/device power; GPU, display, network and helper processes are not aggregated. Missing values are shown as --."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "在可测进程中按系统 CPU 归属能量差值排序,不代表应用或整机完整功耗;不聚合 GPU、屏幕、网络或辅助进程。条形图仅为列表内相对值。"
"value" : "系统 CPU 归属能量差值除以实际统计时长所得的平均功率,不代表应用或整机完整功耗;不聚合 GPU、屏幕、网络或辅助进程。无有效读数显示 --。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "在可測程序中依系統 CPU 歸屬能量差值排序,不代表應用程式或整機完整功耗;不彙總 GPU、螢幕、網路或輔助程序。長條僅為清單內相對值。"
"value" : "系統 CPU 歸屬能量差值除以實際統計時長所得的平均功率,不代表應用程式或整機完整功耗;不彙總 GPU、螢幕、網路或輔助程序。無有效讀數顯示 --。"
}
}
}