补充 GPU 渲染分块、内存与利用率统计,增加只读 SMC 温度及风扇信息和旋转动效。完善电池功率与耗电进程列表,统一首排布局并固定异步加载区域高度。同步验证用例、架构说明和 GPU 能力调研工具。
545 lines
31 KiB
Swift
545 lines
31 KiB
Swift
import SwiftUI
|
|
import AppKit
|
|
|
|
struct MenuPanelView: View {
|
|
let metrics: MetricsStore
|
|
let preferences: AppearancePreferences
|
|
let keepAwake: KeepAwakeService
|
|
let settingsPresentation: SettingsPresentation
|
|
var presentation = PanelPresentation()
|
|
var onOpenSettings: () -> Void = {}
|
|
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
|
@State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760))
|
|
@State private var selectedInterface = ""
|
|
@State private var showAddresses = false
|
|
@State private var showVolumes = false
|
|
|
|
private var snapshot: MetricsSnapshot { metrics.snapshot }
|
|
private var samples: [TrendSample] { metrics.history.samples }
|
|
private var chartIntervals: [TimeInterval] { samples.map(\.expectedInterval) }
|
|
private var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 }
|
|
private var chartBoundaries: Set<Date> { Set(samples.filter(\.breakBefore).map(\.date)) }
|
|
private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 }
|
|
private var firstRowHeight: CGFloat {
|
|
let cardWidth = (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns)
|
|
let groups = CPUCoreGrid.groups(count: snapshot.cpu?.cores.count ?? 0, kinds: CPUCoreTopology.cores)
|
|
let widths = CPUCoreGrid.groupWidths(groups: groups, width: max(0, cardWidth - 20))
|
|
let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
|
|
let extraFanRows = max(0, ((snapshot.fans?.count ?? 0) + 1) / 2 - 1)
|
|
return max(260 + (coreRows >= 3 ? 26 : 0), 260 + CGFloat(extraFanRows) * 19)
|
|
}
|
|
private var network: [NetworkInterfaceMetrics] {
|
|
(snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface }
|
|
}
|
|
private func total(_ key: KeyPath<NetworkInterfaceMetrics, Double?>) -> Double? {
|
|
let rates = network.compactMap { $0[keyPath: key] }
|
|
return !network.isEmpty && rates.count == network.count ? rates.reduce(0, +) : nil
|
|
}
|
|
|
|
var body: some View {
|
|
VStack(spacing: 8) {
|
|
header
|
|
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(height: firstRowHeight)
|
|
gpuCard.frame(height: firstRowHeight)
|
|
batteryCard.frame(height: firstRowHeight)
|
|
memoryCard.frame(minHeight: 240)
|
|
diskCard.frame(minHeight: 250)
|
|
networkCard.frame(minHeight: 250)
|
|
}
|
|
}
|
|
}
|
|
if metrics.isPanelVisible {
|
|
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900, logicalCPUCount: snapshot.cpu?.cores.count ?? 1).frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
.frame(minHeight: 170)
|
|
}
|
|
}
|
|
.padding(10)
|
|
.frame(width: panelSize.width, height: panelSize.height)
|
|
.background(PanelWindowObserver { size in
|
|
if panelSize != size { panelSize = size }
|
|
}.frame(width: 0, height: 0))
|
|
.onAppear { metrics.setPanelVisible(true) }
|
|
.onDisappear { metrics.setPanelVisible(false) }
|
|
.onChange(of: snapshot.network?.map(\.identity)) { _, keys in
|
|
if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" }
|
|
}
|
|
.background(Color("PanelBackground"), in: .rect(cornerRadius: 18))
|
|
.clipShape(.rect(cornerRadius: 18))
|
|
.modifier(AppearanceStyle(preferences: preferences))
|
|
}
|
|
|
|
private var resourceRows: some View {
|
|
VStack(spacing: 8) {
|
|
HStack(alignment: .top, spacing: 8) {
|
|
cpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight)
|
|
gpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight)
|
|
batteryCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight)
|
|
}.frame(height: firstRowHeight)
|
|
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)
|
|
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)
|
|
}
|
|
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)
|
|
}
|
|
Spacer(minLength: 8)
|
|
controls
|
|
}.padding(.horizontal, 4)
|
|
}
|
|
|
|
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, expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
|
}
|
|
private func line(_ key: LocalizedStringKey, _ value: String) -> some View {
|
|
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) }
|
|
}
|
|
|
|
private func coreColor(_ kind: CPUCoreTopology.Kind?) -> Color {
|
|
switch kind {
|
|
case .efficiency: Color("MetricCPU")
|
|
case .middle: Color("MetricMemory")
|
|
case .performance: Color("MetricGPU")
|
|
case nil: .secondary
|
|
}
|
|
}
|
|
|
|
private func coreLabel(_ kind: CPUCoreTopology.Kind) -> Text {
|
|
switch kind {
|
|
case .efficiency: Text("cpu.kind.efficiency", tableName: "CPUDetails")
|
|
case .middle: Text("cpu.kind.performance", tableName: "CPUDetails")
|
|
case .performance:
|
|
CPUCoreTopology.cores.values.contains(.middle)
|
|
? Text("cpu.kind.super", tableName: "CPUDetails")
|
|
: Text("cpu.kind.performance", tableName: "CPUDetails")
|
|
}
|
|
}
|
|
|
|
private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
|
|
if battery.charging { return "battery.chargePower" }
|
|
if !battery.externalPower { return "battery.dischargePower" }
|
|
return "battery.power"
|
|
}
|
|
|
|
private var cpuCard: some View {
|
|
let temperature = snapshot.cpuTemperature
|
|
let highTemperature = CPUTemperatureMonitor.isHighTemperature(temperature)
|
|
return ResourceCard(
|
|
title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"),
|
|
value: MetricFormat.percent(snapshot.cpu?.usage),
|
|
status: temperature.map { "\(Int($0.rounded()))°C" },
|
|
statusWarning: highTemperature,
|
|
statusHelp: temperature == nil ? nil : Text("cpu.temperature.help", tableName: "CPUDetails"),
|
|
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil
|
|
) {
|
|
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu),
|
|
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
|
|
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
|
|
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
|
if let cpu = snapshot.cpu {
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
|
|
Spacer(minLength: 0)
|
|
CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval,
|
|
availableWidth: max(0, (columns == 3 ? PanelLayout.cardWidth(size: panelSize) : (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns)) - 20))
|
|
|
|
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
|
Spacer(minLength: 0)
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
|
|
HStack(spacing: 10) {
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
HStack {
|
|
Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary)
|
|
Spacer(minLength: 3)
|
|
AnimatedMetricText(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).help(Text("cpu.load.help", tableName: "CPUDetails"))
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 25)
|
|
VStack(alignment: .leading, spacing: 3) {
|
|
Text("panel.uptime").foregroundStyle(.secondary)
|
|
AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
|
|
.fontWeight(.medium)
|
|
}
|
|
}.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7)
|
|
|
|
|
|
}
|
|
}
|
|
private 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" },
|
|
statusHelp: Text("gpu.temperatureHelp"),
|
|
detail: snapshot.gpu?.coreCount.map { String(format: String(localized: "gpu.coreCountFormat"), $0) }) {
|
|
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.gpu),
|
|
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
|
|
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
|
|
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
|
|
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
|
if snapshot.gpuUsage == nil { Text("gpu.unavailable").foregroundStyle(.secondary) }
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
|
|
gpuActivity("gpu.rendererActivity", value: snapshot.gpu?.renderer, color: Color("MetricCPU"))
|
|
gpuActivity("gpu.tilerActivity", value: snapshot.gpu?.tiler, color: Color("SeriesSystem"))
|
|
Divider().padding(.vertical, 3)
|
|
Spacer(minLength: 0)
|
|
GPUStatisticsView(inUse: snapshot.gpu?.inUseMemory, allocated: snapshot.gpu?.allocatedMemory,
|
|
average: summary.average, peak: summary.peak)
|
|
Spacer(minLength: 0)
|
|
if let fans = snapshot.fans, !fans.isEmpty {
|
|
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) {
|
|
ForEach(fans) { fan in
|
|
FanSpeedIndicator(title: fans.count == 2 ? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight") : LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm)
|
|
}
|
|
}
|
|
.padding(.horizontal, 7).padding(.vertical, 5)
|
|
.background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6))
|
|
}
|
|
}
|
|
}
|
|
|
|
private func gpuActivity(_ title: LocalizedStringKey, value: Double?, color: Color) -> some View {
|
|
HStack(spacing: 8) {
|
|
Text(title).frame(width: 65, alignment: .leading)
|
|
MetricProgressBar(value: value ?? 0, color: color).frame(height: 5)
|
|
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value)
|
|
AnimatedMetricText(value: MetricFormat.percent(value)).frame(width: 30, alignment: .trailing)
|
|
}.font(.system(size: 10)).help(Text("gpu.pipelineHelp"))
|
|
}
|
|
private var memoryCard: some View {
|
|
ResourceCard(title: "metric.memory", symbol: "memorychip", color: Color("MetricMemory"), value: snapshot.memory.map { String(format: "%.1f / %.1f GB", Double($0.used) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") {
|
|
PanelTrendChart(dates: samples.map(\.date),
|
|
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
|
|
color: Color("MetricMemory"), fixedScale: Double(snapshot.memory?.total ?? 1),
|
|
scaleLabel: MetricFormat.bytes(snapshot.memory?.total), expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
|
if let m = snapshot.memory {
|
|
|
|
GeometryReader { geometry in
|
|
HStack(spacing: 0) {
|
|
ForEach(Array([m.used - min(m.used, m.wired + m.compressed), m.wired, m.compressed, m.total - min(m.total, m.used)].enumerated()), id: \.offset) { i, bytes in
|
|
Rectangle().fill(Color("MetricMemory").opacity([1, 0.75, 0.5, 0.15][i]))
|
|
.frame(width: Double(bytes) / Double(max(1, m.total)) * geometry.size.width)
|
|
}
|
|
}
|
|
}.frame(height: 6).clipped().accessibilityHidden(true)
|
|
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); AnimatedMetricText(value: MetricFormat.percent(m.usage)).foregroundStyle(Color("MetricMemory")) }
|
|
} else { Text("metric.waiting") }
|
|
}
|
|
}
|
|
@ViewBuilder private func pressure(_ value: Int?) -> some View {
|
|
switch value {
|
|
case 1: Text("pressure.normal")
|
|
case 2: Text("pressure.warning").foregroundStyle(.orange)
|
|
case 4: Text("pressure.critical").foregroundStyle(.red)
|
|
default: Text(verbatim: "--")
|
|
}
|
|
}
|
|
private var networkCard: some View {
|
|
ResourceCard(title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: "↓ " + MetricFormat.rate(total(\.download)), secondaryValue: "↑ " + MetricFormat.rate(total(\.upload))) {
|
|
HStack {
|
|
Picker("panel.interface", selection: $selectedInterface) {
|
|
Text("panel.totalNetwork").tag("")
|
|
ForEach(snapshot.network ?? [], id: \.identity) { item in Text(verbatim: item.name).tag(item.identity) }
|
|
}.labelsHidden().controlSize(.mini).frame(maxWidth: 200)
|
|
Spacer(minLength: 0)
|
|
}
|
|
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("MetricMemory"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals).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 {
|
|
case .available: Text("network.pathAvailable").foregroundStyle(.secondary)
|
|
case .unavailable: Text("network.pathUnavailable").foregroundStyle(.secondary)
|
|
case .requiresConnection: Text("network.pathRequiresConnection").foregroundStyle(.secondary)
|
|
case nil: Text("metric.waiting")
|
|
}
|
|
HStack {
|
|
Button("panel.addresses") { showAddresses.toggle() }.popover(isPresented: $showAddresses) {
|
|
VStack(alignment: .leading, spacing: 8) {
|
|
Group {
|
|
ForEach(network, id: \.identity) { item in
|
|
VStack(alignment: .leading, spacing: 3) {
|
|
Text(verbatim: item.name).fontWeight(.medium)
|
|
if item.addresses.isEmpty { Text("panel.addressUnknown") }
|
|
ForEach(item.addresses, id: \.self) { address in
|
|
HStack(alignment: .top) {
|
|
Text(verbatim: address).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
|
|
Spacer(minLength: 0)
|
|
Button { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(address, forType: .string) } label: { Image(systemName: "doc.on.doc") }.accessibilityLabel(Text("panel.copy"))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Text(selectedInterface.isEmpty ? "panel.totalScope" : "panel.interfaceScope").font(.system(size: 9)).foregroundStyle(.secondary)
|
|
}.padding(12).frame(width: 350)
|
|
}
|
|
Spacer()
|
|
Image(systemName: "info.circle").help(Text(selectedInterface.isEmpty ? "panel.totalScope" : "panel.interfaceScope"))
|
|
}
|
|
|
|
}
|
|
}
|
|
private var addressInterface: NetworkInterfaceMetrics? {
|
|
let name = selectedInterface.isEmpty ? snapshot.defaultNetworkInterface : network.first?.name
|
|
return snapshot.network?.first { $0.name == name && $0.active }
|
|
}
|
|
private var networkIntervals: [TimeInterval] { selectedInterface.isEmpty ? chartIntervals : (metrics.history.interfaces[selectedInterface] ?? []).map(\.expectedInterval) }
|
|
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) }
|
|
private var diskCard: some 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("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
|
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" } ?? "--") }
|
|
|
|
|
|
Spacer(minLength: 0)
|
|
Button("disk.volumes") { showVolumes.toggle() }.popover(isPresented: $showVolumes) {
|
|
VStack(alignment: .leading, spacing: 8) {
|
|
Text("disk.homeVolume")
|
|
Text("panel.smartScope").foregroundStyle(.secondary)
|
|
Group {
|
|
ForEach(snapshot.volumes ?? [], id: \.path) { volume in
|
|
VStack(alignment: .leading) {
|
|
Text(verbatim: volume.name).lineLimit(1).truncationMode(.middle)
|
|
line("memory.available", "\(MetricFormat.bytes(volume.capacity.available)) / \(MetricFormat.bytes(volume.capacity.total))")
|
|
}
|
|
}
|
|
Text("panel.apfsScope").font(.system(size: 9)).foregroundStyle(.secondary)
|
|
}
|
|
}.padding(12).frame(width: 330)
|
|
}
|
|
|
|
}
|
|
}
|
|
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 {
|
|
PanelTrendChart(
|
|
dates: samples.map(\.date),
|
|
first: samples.map(\.battery),
|
|
second: samples.map(\.batteryPower),
|
|
color: Color("MetricBattery"),
|
|
secondColor: Color("SeriesUser"),
|
|
fixedScale: 1,
|
|
secondSeriesUsesAutonomousScale: true,
|
|
secondValueFormat: .watts,
|
|
firstLabel: "metric.battery",
|
|
secondLabel: batteryPowerLabel(battery),
|
|
expectedInterval: chartInterval,
|
|
boundaryDates: chartBoundaries,
|
|
intervals: chartIntervals
|
|
)
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
|
|
HStack(alignment: .top, spacing: 10) {
|
|
VStack(spacing: 5) {
|
|
line("battery.health", MetricFormat.percent(battery.health))
|
|
HStack {
|
|
Text("battery.powerSource").foregroundStyle(.secondary)
|
|
Spacer(minLength: 4)
|
|
Text(battery.externalPower ? "battery.acPower" : "battery.batterySource")
|
|
}
|
|
}
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 32)
|
|
VStack(spacing: 5) {
|
|
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
|
|
HStack {
|
|
Text("battery.timeEstimate").foregroundStyle(.secondary)
|
|
Spacer(minLength: 4)
|
|
if battery.externalPower { Text("battery.timeNotApplicable") }
|
|
else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") }
|
|
else { Text("battery.timeUnknown") }
|
|
}
|
|
}
|
|
}
|
|
.font(.system(size: 10))
|
|
.lineLimit(1).minimumScaleFactor(0.72)
|
|
.frame(height: 32)
|
|
Spacer(minLength: 0)
|
|
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
HStack {
|
|
Text("battery.highestEnergyProcess").fontWeight(.semibold)
|
|
Spacer()
|
|
Text("battery.cpuUsage").foregroundStyle(.secondary)
|
|
}
|
|
.font(.system(size: 10))
|
|
let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? []
|
|
if energyProcesses.isEmpty {
|
|
Text("metric.waiting").foregroundStyle(.secondary)
|
|
} else {
|
|
ForEach(energyProcesses) { process in
|
|
EnergyProcessListRow(process: process)
|
|
}
|
|
}
|
|
}
|
|
// Reserve the header and all three rows before process sampling completes.
|
|
.frame(height: 72, alignment: .top)
|
|
.lineLimit(1)
|
|
.help(Text("battery.energyProxyHelp"))
|
|
|
|
} else {
|
|
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
|
|
}
|
|
}
|
|
}
|
|
private var controls: some View {
|
|
HStack(spacing: 8) {
|
|
HStack(spacing: 2) {
|
|
HStack(spacing: 4) {
|
|
Image(systemName: "timer").help(Text("sampling.panel"))
|
|
IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 }))
|
|
}.padding(.horizontal, 6).accessibilityLabel(Text("sampling.panel"))
|
|
Divider().frame(height: 18).padding(.horizontal, 3)
|
|
Button { presentation.isPinned.toggle() } label: {
|
|
Image(systemName: presentation.isPinned ? "pin.fill" : "pin")
|
|
.frame(width: 20, height: 20)
|
|
.foregroundStyle(presentation.isPinned ? preferences.tintColor : Color.primary)
|
|
}
|
|
.help(Text(presentation.isPinned ? "panel.unpin" : "panel.pin"))
|
|
.accessibilityLabel(Text(presentation.isPinned ? "panel.unpin" : "panel.pin"))
|
|
.accessibilityValue(Text(presentation.isPinned ? "panel.pinned" : "panel.unpinned"))
|
|
Button { keepAwake.toggle() } label: {
|
|
Image(systemName: keepAwake.isEnabled ? "cup.and.saucer.fill" : "cup.and.saucer")
|
|
.frame(width: 20, height: 20)
|
|
.foregroundStyle(keepAwake.isEnabled ? preferences.tintColor : Color.primary)
|
|
}
|
|
.help(keepAwake.didFail ? Text("awake.failed") : (keepAwake.isEnabled ? Text("awake.disable") : Text("awake.enable")))
|
|
.accessibilityLabel(keepAwake.isEnabled ? Text("awake.disable") : Text("awake.enable"))
|
|
.accessibilityValue(keepAwake.isEnabled ? Text("awake.on") : Text("awake.off"))
|
|
Button { metrics.togglePause() } label: {
|
|
Image(systemName: metrics.isPaused ? "play.fill" : "pause.fill").frame(width: 20, height: 20)
|
|
}
|
|
.help(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
|
|
.accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
|
|
Button {
|
|
NSApp.setActivationPolicy(.regular)
|
|
settingsPresentation.request()
|
|
onOpenSettings()
|
|
} label: {
|
|
Image(systemName: "gearshape").frame(width: 20, height: 20)
|
|
}
|
|
.help(Text("action.settings")).accessibilityLabel(Text("action.settings"))
|
|
Divider().frame(height: 18).padding(.horizontal, 3)
|
|
Button { NSApp.terminate(nil) } label: {
|
|
Image(systemName: "power").frame(width: 20, height: 20)
|
|
}
|
|
.help(Text("action.quit")).accessibilityLabel(Text("action.quit"))
|
|
}
|
|
.buttonStyle(PanelControlButtonStyle())
|
|
.padding(4)
|
|
.glassEffect(.regular, in: .capsule)
|
|
}
|
|
.controlSize(.small)
|
|
.padding(.horizontal, 2).padding(.vertical, 0)
|
|
}
|
|
}
|
|
|
|
private struct EnergyProcessListRow: View {
|
|
let process: ProcessMetrics
|
|
@State private var icon: NSImage?
|
|
|
|
private var progress: Double {
|
|
guard let value = process.cpu, value.isFinite else { return 0 }
|
|
return min(max(value, 0), 1)
|
|
}
|
|
|
|
var body: some View {
|
|
HStack(spacing: 5) {
|
|
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)
|
|
Text(verbatim: 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)
|
|
.animation(.easeInOut(duration: 0.35), value: process.cpu)
|
|
AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--")
|
|
.foregroundStyle(Color("MetricCPU"))
|
|
.monospacedDigit().frame(width: 39, alignment: .trailing)
|
|
}
|
|
.font(.system(size: 10))
|
|
.frame(height: 16)
|
|
.task(id: process.id) {
|
|
icon = NSRunningApplication(processIdentifier: process.id.pid)?.icon
|
|
if icon == nil, let path = process.path {
|
|
icon = NSWorkspace.shared.icon(forFile: path)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
private struct PanelControlButtonStyle: ButtonStyle {
|
|
func makeBody(configuration: Configuration) -> some View {
|
|
PanelControlButtonBody(isPressed: configuration.isPressed) {
|
|
configuration.label
|
|
}
|
|
}
|
|
}
|
|
|
|
private struct PanelControlButtonBody<Content: View>: View {
|
|
let isPressed: Bool
|
|
@ViewBuilder var content: () -> Content
|
|
@State private var isHovered = false
|
|
|
|
var body: some View {
|
|
content()
|
|
.frame(width: 26, height: 24)
|
|
.background {
|
|
Circle().fill(.primary.opacity(isPressed ? 0.16 : (isHovered ? 0.08 : 0)))
|
|
}
|
|
.contentShape(Circle())
|
|
.onHover { isHovered = $0 }
|
|
}
|
|
}
|