Files
Kymo/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift
T

223 lines
12 KiB
Swift

import AppKit
import SwiftUI
extension MenuPanelView {
func line(_ key: LocalizedStringKey, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text(key).font(.system(size: 10)).foregroundStyle(.secondary)
Spacer(minLength: 6)
MetricText(value: value).font(.system(size: 10, weight: .medium))
}.frame(height: 16)
}
func inlineMetric(_ title: LocalizedStringKey, _ value: String) -> some View {
HStack(spacing: 4) {
Text(title).foregroundStyle(.secondary)
MetricText(value: value).fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1)
}
func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
}
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,
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil,
chart: {
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, stackOrder: [2, 1])
}
) {
HStack(spacing: 5) {
inlineMetric("cpu.user", MetricFormat.percent(snapshot.cpu?.user))
inlineMetric("cpu.system", MetricFormat.percent(snapshot.cpu?.system))
}.frame(height: 16)
if let cpu = snapshot.cpu {
CPUCoreGrid(
values: cpu.cores, kinds: CPUCoreTopology.cores,
availableWidth: cardContentWidth)
} else {
Text("metric.waiting").foregroundStyle(.secondary)
}
}
}
var gpuCard: some View {
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" },
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map { $0.gpu.map { max(0, 1 - $0) } },
third: samples.map(\.gpuRenderer), fourth: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MemoryAvailable"),
thirdColor: Color("MetricCPU"), fourthColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.idle", thirdLabel: "gpu.renderer", fourthLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [0, 1])
}
) {
HStack(spacing: 5) {
if let count = snapshot.gpu?.coreCount {
Text(verbatim: String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), count))
.foregroundStyle(.primary)
}
}.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9).frame(height: 16)
let fans = displayedFans
if !fans.isEmpty {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 5, alignment: .leading), count: min(2, fans.count)), spacing: 2) {
ForEach(fans) { fan in
FanSpeedIndicator(
title: fans.count == 2
? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight"))
: Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm,
isActive: metrics.isPanelVisible && !metrics.isPaused && !metrics.isSystemSleeping && !metrics.isDisplaySleeping)
.frame(height: 16)
}
}
} else if snapshot.fans == nil {
Text("metric.waiting").font(.system(size: 10))
.frame(maxWidth: .infinity, alignment: .leading).frame(height: 16)
}
}
}
var memoryCard: some View {
let header = MemoryHeaderInfo(memory: snapshot.memory, locale: locale)
return ResourceCard(
title: "metric.memory", symbol: "memorychip", color: Color("MemoryApplication"),
value: snapshot.memory.map {
String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824)
} ?? "--",
detail: header.badgeTitle, detailColor: snapshot.memory?.pressure == 1 ? Color("MetricBattery") : header.color,
detailHelp: header.help + "\n" + MetricFormat.percent(snapshot.memory?.usage),
chart: {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed),
color: Color("MemoryApplication"), secondColor: Color("MemoryApplication"),
thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1),
firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [1, 2, 3])
}
) {
if let memory = snapshot.memory {
MemoryDetailsView(memory: memory)
} else {
Text("metric.waiting").foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
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)
} ?? "--",
headerAccessory: AnyView(Button { showVolumes.toggle() } label: {
HStack(spacing: 2) { Text("disk.localVolumes"); Image(systemName: "chevron.right").font(.system(size: 7)) }
}.font(.system(size: 10)).buttonStyle(.plain).help(Text("disk.viewDetails"))),
chart: {
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, projection: .split(upwardSeries: 0)
)
}
) {
StorageDetailsView(disk: snapshot.disk, health: snapshot.diskHealth, io: snapshot.diskIO)
.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: 10)).foregroundStyle(.secondary)
}
}.padding(12).frame(width: 330)
.environment(\.locale, locale)
}
}
}
var batteryCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
value: MetricFormat.percent(snapshot.battery?.charge),
status: snapshot.battery.map { AppLocalization.string($0.externalPower ? "battery.acPower" : "battery.batterySource", locale: locale) },
chart: {
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: snapshot.battery.map(batteryPowerLabel) ?? "battery.power",
expectedInterval: chartInterval,
boundaryDates: chartBoundaries,
intervals: chartIntervals
)
}
) {
inlineMetric("battery.powerShort", MetricFormat.watts(snapshot.battery?.power))
.frame(height: 16)
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
.font(.system(size: 10)).frame(maxWidth: .infinity).frame(height: 32)
}
}
}
private func batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
inlineMetric("battery.healthShort", MetricFormat.percent(battery.health))
inlineMetric("battery.cyclesShort", battery.cycles.map(String.init) ?? "--")
}
HStack(spacing: 4) {
Text("battery.timeShort").foregroundStyle(.secondary)
if battery.externalPower {
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
} else if let minutes = battery.minutesRemaining {
MetricText(value: "\(minutes) min")
} else {
Text("battery.timeUnknown")
}
}
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9)
}
}