feat(menubar): 实现统一资源面板与独立滚动进程表
This commit is contained in:
@@ -7,188 +7,216 @@ struct MenuPanelView: View {
|
||||
let keepAwake: KeepAwakeService
|
||||
let settingsPresentation: SettingsPresentation
|
||||
@Environment(\.openSettings) private var openSettings
|
||||
@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 columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 }
|
||||
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: 4) {
|
||||
VStack(spacing: 2) {
|
||||
MetricRow(title: "metric.cpu", symbol: "cpu", value: MetricFormat.percent(metrics.snapshot.cpu?.usage),
|
||||
usage: metrics.snapshot.cpu?.usage, history: metrics.history.samples.map(\.cpu), accent: preferences.tintColor) {
|
||||
cpuDetail
|
||||
}
|
||||
MetricRow(title: "metric.gpu", symbol: "square.grid.2x2", value: MetricFormat.percent(metrics.snapshot.gpuUsage),
|
||||
usage: metrics.snapshot.gpuUsage, history: metrics.history.samples.map(\.gpu), accent: preferences.tintColor) {
|
||||
Text("gpu.unavailable").foregroundStyle(.secondary)
|
||||
}
|
||||
MetricRow(title: "metric.memory", symbol: "memorychip", value: MetricFormat.percent(metrics.snapshot.memory?.usage),
|
||||
usage: metrics.snapshot.memory?.usage, history: metrics.history.samples.map(\.memory), accent: preferences.tintColor) {
|
||||
memoryDetail
|
||||
}
|
||||
VStack(spacing: 10) {
|
||||
header
|
||||
ScrollView {
|
||||
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12, alignment: .top), count: columns), alignment: .leading, spacing: 12) {
|
||||
cpuCard
|
||||
gpuCard
|
||||
memoryCard
|
||||
networkCard
|
||||
diskCard
|
||||
batteryCard
|
||||
}.padding(.trailing, 2)
|
||||
}
|
||||
VStack(spacing: 2) {
|
||||
MetricRow(title: "metric.network", symbol: "network", value: networkValue,
|
||||
usage: metrics.snapshot.downloadRate.map { _ in 0 }, history: networkHistory, accent: preferences.tintColor) {
|
||||
ScrollView {
|
||||
VStack(spacing: 6) {
|
||||
switch metrics.snapshot.networkPath {
|
||||
case .available: Text("network.pathAvailable")
|
||||
case .unavailable: Text("network.pathUnavailable")
|
||||
case .requiresConnection: Text("network.pathRequiresConnection")
|
||||
case nil: Text("metric.waiting")
|
||||
}
|
||||
if let interfaces = metrics.snapshot.network {
|
||||
if interfaces.isEmpty { Text("network.noLink") }
|
||||
ForEach(interfaces, id: \.name) { item in
|
||||
VStack(spacing: 4) {
|
||||
Text(verbatim: item.name).fontWeight(.semibold)
|
||||
detailLine("network.download", rate(item.download))
|
||||
detailLine("network.upload", rate(item.upload))
|
||||
detailLine("network.received", MetricFormat.bytes(item.received))
|
||||
detailLine("network.sent", MetricFormat.bytes(item.sent))
|
||||
}
|
||||
}
|
||||
} else { Text("metric.waiting") }
|
||||
}
|
||||
}.frame(maxHeight: 280)
|
||||
}
|
||||
MetricRow(title: "metric.disk", symbol: "internaldrive", value: MetricFormat.percent(metrics.snapshot.disk?.usage),
|
||||
usage: metrics.snapshot.disk?.usage, history: metrics.history.samples.map(\.disk), accent: preferences.tintColor) {
|
||||
ScrollView {
|
||||
VStack(spacing: 6) {
|
||||
Text("disk.homeVolume").foregroundStyle(.secondary)
|
||||
detailLine("disk.total", MetricFormat.bytes(metrics.snapshot.disk?.total))
|
||||
detailLine("memory.available", MetricFormat.bytes(metrics.snapshot.disk?.available))
|
||||
detailLine("disk.remainingLife", MetricFormat.percent(metrics.snapshot.diskHealth?.remainingLife))
|
||||
HStack {
|
||||
Text("disk.powerOnHours").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
if let hours = metrics.snapshot.diskHealth?.powerOnHours {
|
||||
Text("disk.hours \(hours)").monospacedDigit()
|
||||
} else { Text(verbatim: "--") }
|
||||
}
|
||||
Divider()
|
||||
Text("disk.physicalIO").foregroundStyle(.secondary)
|
||||
detailLine("disk.read", rate(metrics.snapshot.diskIO?.read))
|
||||
detailLine("disk.write", rate(metrics.snapshot.diskIO?.written))
|
||||
Divider()
|
||||
Text("disk.volumes").foregroundStyle(.secondary)
|
||||
if let volumes = metrics.snapshot.volumes {
|
||||
ForEach(volumes, id: \.path) { volume in
|
||||
VStack(spacing: 4) {
|
||||
Text(verbatim: volume.name).fontWeight(.semibold)
|
||||
detailLine("disk.total", MetricFormat.bytes(volume.capacity.total))
|
||||
detailLine("memory.available", MetricFormat.bytes(volume.capacity.available))
|
||||
}
|
||||
}
|
||||
} else { Text("metric.waiting") }
|
||||
}
|
||||
}.frame(maxHeight: 280)
|
||||
}
|
||||
if let battery = metrics.snapshot.battery {
|
||||
MetricRow(title: "metric.battery", symbol: battery.charging ? "battery.100percent.bolt" : "battery.100percent",
|
||||
value: MetricFormat.percent(battery.charge), usage: battery.charge.map { _ in 0 }, history: metrics.history.samples.map(\.battery), accent: preferences.tintColor) {
|
||||
VStack(spacing: 6) {
|
||||
Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging")
|
||||
if battery.externalPower && !battery.charging {
|
||||
HStack {
|
||||
Text("battery.timeEstimate").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("battery.timeNotApplicable")
|
||||
}
|
||||
} else if let minutes = battery.minutesRemaining {
|
||||
detailLine(battery.charging ? "battery.timeFull" : "battery.timeEmpty", "\(minutes) min")
|
||||
} else {
|
||||
HStack {
|
||||
Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("battery.timeUnknown")
|
||||
}
|
||||
}
|
||||
detailLine("battery.cycles", battery.cycles.map(String.init) ?? "--")
|
||||
detailLine("battery.health", MetricFormat.percent(battery.health))
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
if metrics.isPanelVisible {
|
||||
ProcessTableView(snapshot: snapshot.processes)
|
||||
.frame(height: min(300, max(220, panelSize.height * 0.36)))
|
||||
}
|
||||
Divider().padding(.horizontal, 10)
|
||||
HStack {
|
||||
Text("system.load")
|
||||
Text(verbatim: metrics.snapshot.load.map(MetricFormat.decimal).joined(separator: " / "))
|
||||
Spacer(minLength: 4)
|
||||
Image(systemName: "clock")
|
||||
Text(verbatim: String(format: "%.0fh", floor(metrics.snapshot.uptime / 3600)))
|
||||
}
|
||||
.font(.system(size: 10)).monospacedDigit().foregroundStyle(.secondary)
|
||||
.padding(.horizontal, 10).padding(.vertical, 8)
|
||||
footer
|
||||
}
|
||||
.padding(10)
|
||||
.frame(width: 320)
|
||||
.padding(12)
|
||||
.frame(width: panelSize.width, height: panelSize.height)
|
||||
.background(PanelWindowObserver { size, visible in
|
||||
if panelSize != size { panelSize = size }
|
||||
if metrics.isPanelVisible != visible { metrics.setPanelVisible(visible) }
|
||||
}.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 = "" }
|
||||
}
|
||||
.modifier(AppearanceStyle(preferences: preferences))
|
||||
}
|
||||
|
||||
// Shared scale for the whole visible history; never label throughput as utilization.
|
||||
private var networkHistory: [Double?] {
|
||||
let values = metrics.history.samples.map(\.download)
|
||||
let scale = max(1_000, values.compactMap { $0 }.max() ?? 1_000)
|
||||
return values.map { $0.map { $0 / scale } }
|
||||
private var header: some View {
|
||||
HStack(spacing: 10) {
|
||||
Image("BrandMark").renderingMode(.template)
|
||||
Text("Kymo").font(.system(size: 18, weight: .semibold))
|
||||
if panelSize.width >= 900 {
|
||||
Text(verbatim: "\(ProcessInfo.processInfo.processorCount) CPU · \(MetricFormat.bytes(snapshot.memory?.total))")
|
||||
.font(.system(size: 11)).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
VStack(alignment: .trailing, spacing: 2) {
|
||||
Label(metrics.isPaused ? "panel.paused" : "panel.sampling", systemImage: metrics.isPaused ? "pause.circle" : "circle.fill")
|
||||
.foregroundStyle(metrics.isPaused ? Color.secondary : Color("MetricBattery"))
|
||||
Text(snapshot.date, style: .time).foregroundStyle(.secondary)
|
||||
}.font(.system(size: 10))
|
||||
}.padding(.horizontal, 4)
|
||||
}
|
||||
|
||||
private var networkValue: String {
|
||||
guard let total = metrics.snapshot.downloadRate else { return "--" }
|
||||
return total >= 1_000_000 ? String(format: "%.1fM↓", total / 1_000_000) : String(format: "%.0fK↓", total / 1000)
|
||||
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color) -> some View {
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color)
|
||||
}
|
||||
private func line(_ key: LocalizedStringKey, _ value: String) -> some View {
|
||||
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); Text(verbatim: value).monospacedDigit() }
|
||||
}
|
||||
|
||||
private func rate(_ bytes: Double?) -> String {
|
||||
MetricFormat.rate(bytes)
|
||||
private var cpuCard: some View {
|
||||
ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) {
|
||||
chart(\.cpu, color: Color("MetricCPU"))
|
||||
if let cpu = snapshot.cpu {
|
||||
HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) }
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 28), spacing: 4)], spacing: 4) {
|
||||
ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, value in
|
||||
Text(verbatim: "\(index + 1)").font(.system(size: 9)).frame(maxWidth: .infinity).frame(height: 18)
|
||||
.background(Color("MetricCPU").opacity(0.12 + value * 0.65), in: .rect(cornerRadius: 3))
|
||||
.help("\(index + 1): \(MetricFormat.percent(value))")
|
||||
.accessibilityLabel(Text("cpu.core")).accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
|
||||
}
|
||||
}
|
||||
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
line("system.load", snapshot.load.map(MetricFormat.decimal).joined(separator: " / "))
|
||||
line("panel.uptime", String(format: "%.1f h", snapshot.uptime / 3600))
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var cpuDetail: some View {
|
||||
if let cpu = metrics.snapshot.cpu {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
detailLine("cpu.user", MetricFormat.percent(cpu.user))
|
||||
detailLine("cpu.system", MetricFormat.percent(cpu.system))
|
||||
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 4) {
|
||||
ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, usage in
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(preferences.tintColor.opacity(0.12 + 0.88 * usage))
|
||||
.frame(height: 18)
|
||||
.overlay(Text(verbatim: "\(index + 1)").font(.system(size: 9)).foregroundStyle(.primary))
|
||||
.help(MetricFormat.percent(usage))
|
||||
.accessibilityLabel(Text("cpu.core"))
|
||||
.accessibilityValue(Text(verbatim: "\(index + 1): \(MetricFormat.percent(usage))"))
|
||||
private var gpuCard: some View {
|
||||
ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage)) {
|
||||
chart(\.gpu, color: Color("MetricGPU"))
|
||||
if snapshot.gpuUsage == nil { Text("gpu.unavailable").foregroundStyle(.secondary) }
|
||||
line("panel.gpuCores", snapshot.gpu?.coreCount.map(String.init) ?? "--")
|
||||
Label("panel.gpuPerCore", systemImage: "info.circle").foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
Text("panel.gpuSource").font(.system(size: 10)).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
private var memoryCard: some View {
|
||||
ResourceCard(title: "metric.memory", symbol: "memorychip", color: Color("MetricMemory"), value: MetricFormat.percent(snapshot.memory?.usage)) {
|
||||
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))
|
||||
if let m = snapshot.memory {
|
||||
line("memory.used", "\(MetricFormat.bytes(m.used)) / \(MetricFormat.bytes(m.total))")
|
||||
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) }
|
||||
} 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))) {
|
||||
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(.small)
|
||||
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), fixedScale: nil).id(selectedInterface)
|
||||
if !network.isEmpty && total(\.download) == nil { Text("panel.rateBaseline").foregroundStyle(.secondary) }
|
||||
HStack { line("network.download", MetricFormat.rate(total(\.download))); line("network.upload", MetricFormat.rate(total(\.upload))) }
|
||||
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")
|
||||
}
|
||||
DisclosureGroup("panel.addresses", isExpanded: $showAddresses) {
|
||||
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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
Text(selectedInterface.isEmpty ? "panel.totalScope" : "panel.interfaceScope").font(.system(size: 9)).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var memoryDetail: some View {
|
||||
if let memory = metrics.snapshot.memory {
|
||||
VStack(spacing: 6) {
|
||||
detailLine("memory.used", MetricFormat.bytes(memory.used))
|
||||
detailLine("memory.available", MetricFormat.bytes(memory.total - memory.used))
|
||||
detailLine("memory.app", MetricFormat.bytes(memory.used - min(memory.used, memory.wired + memory.compressed)))
|
||||
detailLine("memory.wired", MetricFormat.bytes(memory.wired))
|
||||
detailLine("memory.compressed", MetricFormat.bytes(memory.compressed))
|
||||
detailLine("memory.swap", MetricFormat.bytes(memory.swapUsed))
|
||||
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: MetricFormat.percent(snapshot.disk?.usage)) {
|
||||
Text("disk.homeVolume").foregroundStyle(.secondary)
|
||||
line("memory.used", snapshot.disk.map { "\(MetricFormat.bytes($0.total - min($0.total, $0.available))) / \(MetricFormat.bytes($0.total))" } ?? "--")
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil)
|
||||
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" } ?? "--") }
|
||||
Text("panel.smartScope").font(.system(size: 9)).foregroundStyle(.secondary)
|
||||
if let date = snapshot.diskHealthDate { Text(date, style: .time).font(.system(size: 9)).foregroundStyle(.secondary) }
|
||||
DisclosureGroup("disk.volumes", isExpanded: $showVolumes) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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 {
|
||||
chart(\.battery, color: Color("MetricBattery"))
|
||||
Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging")
|
||||
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
|
||||
line("battery.health", MetricFormat.percent(battery.health))
|
||||
HStack {
|
||||
Text("memory.pressure").foregroundStyle(.secondary)
|
||||
Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
switch memory.pressure {
|
||||
case 1: Text("pressure.normal")
|
||||
case 2: Text("pressure.warning").foregroundStyle(.orange)
|
||||
case 4: Text("pressure.critical").foregroundStyle(.red)
|
||||
default: Text(verbatim: "--")
|
||||
}
|
||||
if battery.externalPower && !battery.charging { Text("battery.timeNotApplicable") }
|
||||
else if let minutes = battery.minutesRemaining { Text(verbatim: "\(minutes) min") }
|
||||
else { Text("battery.timeUnknown") }
|
||||
}
|
||||
if let date = snapshot.batteryHealthDate { Text(date, style: .time).font(.system(size: 9)).foregroundStyle(.secondary) }
|
||||
} else {
|
||||
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
|
||||
}
|
||||
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
}
|
||||
}
|
||||
|
||||
private func detailLine(_ key: LocalizedStringKey, _ value: String) -> some View {
|
||||
HStack { Text(key).foregroundStyle(.secondary); Spacer(); Text(verbatim: value).monospacedDigit() }
|
||||
}
|
||||
|
||||
private var footer: some View {
|
||||
HStack(spacing: 8) {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
|
||||
nonisolated enum PanelLayout {
|
||||
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))))
|
||||
}
|
||||
static func constrainedFrame(_ frame: CGRect, visible: CGRect) -> CGRect {
|
||||
let safe = visible.insetBy(dx: 16, dy: 16)
|
||||
let width = min(frame.width, safe.width), height = min(frame.height, safe.height)
|
||||
return CGRect(x: min(max(frame.minX, safe.minX), safe.maxX - width),
|
||||
y: min(max(frame.minY, safe.minY), safe.maxY - height), width: width, height: height)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// Window geometry/lifecycle stays in the feature layer; Core receives only visibility.
|
||||
struct PanelWindowObserver: NSViewRepresentable {
|
||||
var update: (CGSize, Bool) -> Void
|
||||
func makeNSView(context: Context) -> ObserverView { ObserverView(update: update) }
|
||||
func updateNSView(_ view: ObserverView, context: Context) { view.update = update }
|
||||
|
||||
final class ObserverView: NSView {
|
||||
var update: (CGSize, Bool) -> Void
|
||||
private var observers: [NSObjectProtocol] = []
|
||||
init(update: @escaping (CGSize, Bool) -> Void) { self.update = update; super.init(frame: .zero) }
|
||||
required init?(coder: NSCoder) { fatalError() }
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
observers.forEach(NotificationCenter.default.removeObserver)
|
||||
observers = []
|
||||
guard let window else { return }
|
||||
for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification, NSWindow.didBecomeKeyNotification,
|
||||
NSWindow.didResignKeyNotification, NSWindow.willCloseNotification,
|
||||
NSWindow.didChangeOcclusionStateNotification] {
|
||||
observers.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.report() }
|
||||
})
|
||||
}
|
||||
observers.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.report() }
|
||||
})
|
||||
report()
|
||||
}
|
||||
private func report() {
|
||||
guard let window else { return }
|
||||
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 visible = window.isVisible && window.occlusionState.contains(.visible)
|
||||
DispatchQueue.main.async { [weak self, weak window] in
|
||||
guard let self, let window else { return }
|
||||
self.update(size, visible)
|
||||
// SwiftUI can resize a MenuBarExtra after the system chose its anchor origin.
|
||||
// Clamp after layout as well as on moves; keep the native status-item scene.
|
||||
DispatchQueue.main.async { [weak window] in
|
||||
guard let window, window.isVisible else { return }
|
||||
let adjusted = PanelLayout.constrainedFrame(window.frame, visible: frame)
|
||||
if abs(adjusted.minX - window.frame.minX) > 0.5 || abs(adjusted.minY - window.frame.minY) > 0.5 {
|
||||
window.setFrameOrigin(adjusted.origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
deinit { observers.forEach(NotificationCenter.default.removeObserver) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
|
||||
/// Compute once per data/filter/sort event, never from row rendering or scroll position.
|
||||
nonisolated enum ProcessTableProjection {
|
||||
static func rows(_ input: [ProcessMetrics], query: String, byMemory: Bool, order: [ProcessIdentity]) -> [ProcessMetrics] {
|
||||
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
|
||||
return input.filter {
|
||||
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false)
|
||||
}.sorted {
|
||||
let aRank = ranks[$0.id] ?? Int.max, bRank = ranks[$1.id] ?? Int.max
|
||||
if aRank != bRank { return aRank < bRank }
|
||||
let a = byMemory ? $0.residentBytes.map(Double.init) ?? -1 : $0.cpu ?? -1
|
||||
let b = byMemory ? $1.residentBytes.map(Double.init) ?? -1 : $1.cpu ?? -1
|
||||
if a != b { return a > b }
|
||||
return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
struct ProcessTableView: View {
|
||||
let snapshot: ProcessSnapshot?
|
||||
@State private var search = ""
|
||||
@State private var byMemory = false
|
||||
@State private var hovering = false
|
||||
@State private var selected: ProcessIdentity?
|
||||
@State private var rows: [ProcessMetrics] = []
|
||||
@State private var departed: ProcessMetrics?
|
||||
@FocusState private var searchFocused: Bool
|
||||
|
||||
private var held: Bool { hovering || selected != nil || searchFocused || !search.isEmpty }
|
||||
private var selectedRow: ProcessMetrics? { rows.first { $0.id == selected } }
|
||||
private var exitedSelection: ProcessIdentity? {
|
||||
guard let selected, snapshot != nil, !rows.contains(where: { $0.id == selected }) else { return nil }
|
||||
return selected
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Label("panel.processes", systemImage: "list.bullet.rectangle").fontWeight(.semibold)
|
||||
Text(verbatim: "\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)")
|
||||
.foregroundStyle(.secondary).help(Text("panel.coverage"))
|
||||
Spacer(minLength: 0)
|
||||
if held { Button("panel.liveSort") { selected = nil; rebuild(retainOrder: false) } }
|
||||
Picker("panel.sort", selection: $byMemory) {
|
||||
Text("CPU %").tag(false)
|
||||
Text("panel.rss").tag(true)
|
||||
}.labelsHidden().frame(width: 100)
|
||||
}
|
||||
HStack {
|
||||
Text("panel.processScope").font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(2)
|
||||
Spacer(minLength: 4)
|
||||
TextField("panel.search", text: $search).textFieldStyle(.roundedBorder)
|
||||
.frame(width: 210).focused($searchFocused)
|
||||
}
|
||||
if snapshot?.failed == true { Text("panel.processFailed") }
|
||||
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
// Native Table owns its vertical/horizontal scrolling and recycles visible cells.
|
||||
Table(rows, selection: $selected) {
|
||||
TableColumn("PID") { row in Text(verbatim: "\(row.id.pid)") }.width(48)
|
||||
TableColumn("panel.name") { row in Text(verbatim: row.name).lineLimit(1) }.width(min: 90, ideal: 140, max: 180)
|
||||
TableColumn("panel.path") { row in Text(verbatim: row.path ?? "--").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) }.width(min: 150, ideal: 400)
|
||||
TableColumn("CPU %") { row in Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--") }.width(62)
|
||||
TableColumn("panel.rss") { row in Text(verbatim: row.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--") }.width(85)
|
||||
TableColumn("panel.threads") { row in
|
||||
HStack { Text(verbatim: row.threads.map(String.init) ?? "--"); if row.restricted { Image(systemName: "lock").accessibilityLabel(Text("panel.restricted")) } }
|
||||
}.width(65)
|
||||
}
|
||||
.font(.system(size: 11)).monospacedDigit()
|
||||
.tableStyle(.inset(alternatesRowBackgrounds: true))
|
||||
.transaction { $0.animation = nil }
|
||||
.overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } }
|
||||
if let row = selectedRow {
|
||||
HStack(alignment: .top) {
|
||||
Text(verbatim: row.path ?? "--").textSelection(.enabled).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)
|
||||
if let path = row.path { Button("panel.copy") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(path, forType: .string) } }
|
||||
}.font(.system(size: 11))
|
||||
} else if exitedSelection != nil, let departed {
|
||||
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { selected = nil; self.departed = nil } }
|
||||
}
|
||||
}
|
||||
.font(.system(size: 12)).padding(10)
|
||||
.background(Color("PanelCard"), in: .rect(cornerRadius: 14))
|
||||
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.primary.opacity(0.1)))
|
||||
.onAppear { rebuild(retainOrder: false) }
|
||||
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held) }
|
||||
.onChange(of: search) { _, _ in rebuild(retainOrder: held) }
|
||||
.onChange(of: byMemory) { _, _ in rebuild(retainOrder: false) }
|
||||
.onChange(of: selected) { _, _ in if let row = selectedRow { 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 selected == id { selected = nil; departed = nil }
|
||||
}
|
||||
.onExitCommand {
|
||||
if !search.isEmpty { search = "" }
|
||||
else if selected != nil { selected = nil; departed = nil }
|
||||
else if searchFocused { searchFocused = false }
|
||||
else { NSApp.keyWindow?.close() }
|
||||
}
|
||||
}
|
||||
private func rebuild(retainOrder: Bool) {
|
||||
rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, byMemory: byMemory, order: retainOrder ? rows.map(\.id) : [])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user