refactor(process): 简化进程表并统一表头排序与应用图标

This commit is contained in:
2026-11-03 19:24:13 +08:00
parent 1419bbbe09
commit 1b903efb5c
8 changed files with 121 additions and 67 deletions
@@ -269,7 +269,6 @@ extension MenuPanelView {
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 }
@@ -278,15 +277,7 @@ struct EnergyProcessListRow: View {
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)
ProcessIcon(process: process)
Text(verbatim: process.name).lineLimit(1).truncationMode(.middle)
.frame(width: 66, alignment: .leading)
GeometryReader { proxy in
@@ -306,11 +297,6 @@ struct EnergyProcessListRow: View {
}
.font(PanelStyle.label)
.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)
}
}
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ struct MenuPanelView: View {
resourceRows
}
if metrics.isPanelVisible {
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900, logicalCPUCount: snapshot.cpu?.cores.count ?? 1).frame(maxWidth: .infinity, maxHeight: .infinity)
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(minHeight: 170)
}
}
+28
View File
@@ -0,0 +1,28 @@
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 ?? "")") {
// Resolve by the sampled executable, avoiding an icon from a reused PID.
guard let path = process.path else { icon = nil; return }
let url = URL(fileURLWithPath: path)
let app = sequence(first: url, next: { $0.path == "/" ? nil : $0.deletingLastPathComponent() })
.first { $0.pathExtension == "app" }
icon = NSWorkspace.shared.icon(forFile: (app ?? url).path)
}
}
}
@@ -2,17 +2,49 @@ 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] {
static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], 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 }
for comparator in sorting {
let result = comparator.compare($0, $1)
if result != .orderedSame { return result == .orderedAscending }
}
return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name
}
}
}
/// 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 }
let key: Key
var order: SortOrder = .reverse
func compare(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> ComparisonResult {
func metric(_ a: Double?, _ b: Double?) -> ComparisonResult {
switch (a, b) {
case (nil, nil): return .orderedSame
case (nil, _): return .orderedDescending
case (_, nil): return .orderedAscending
case let (a?, b?): return directed(a < b ? .orderedAscending : a > b ? .orderedDescending : .orderedSame)
}
}
switch key {
case .pid: return metric(Double(lhs.id.pid), Double(rhs.id.pid))
case .name: return directed(lhs.name.localizedStandardCompare(rhs.name))
case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? ""))
case .cpu: return metric(lhs.cpu, rhs.cpu)
case .memory: return metric(lhs.residentBytes.map { Double($0) }, rhs.residentBytes.map { Double($0) })
case .threads: return metric(lhs.threads.map { Double($0) }, rhs.threads.map { Double($0) })
}
}
private func directed(_ value: ComparisonResult) -> ComparisonResult {
guard order == .reverse else { return value }
return value == .orderedAscending ? .orderedDescending : value == .orderedDescending ? .orderedAscending : .orderedSame
}
}
+23 -41
View File
@@ -4,9 +4,8 @@ import AppKit
struct ProcessTableView: View {
let snapshot: ProcessSnapshot?
var wide: Bool = true
var logicalCPUCount: Int = 1
@State private var search = ""
@State private var byMemory = false
@State private var sortOrder = [ProcessSort(key: .cpu)]
@State private var hovering = false
@State private var selected: ProcessIdentity?
@State private var rows: [ProcessMetrics] = []
@@ -22,35 +21,26 @@ struct ProcessTableView: View {
var body: some View {
VStack(alignment: .leading, spacing: 6) {
if wide {
HStack(spacing: 10) {
processTitle
Image(systemName: "info.circle").foregroundStyle(.secondary).help(Text("panel.processScope"))
Spacer(minLength: 0)
if held { Button { selected = nil; rebuild(retainOrder: false) } label: { Image(systemName: "arrow.up.arrow.down") }.help(Text("panel.liveSort")) }
searchField.frame(width: 220)
sorting.frame(width: 160)
}
} else {
HStack { processTitle; Spacer(); sorting.frame(width: 140) }
searchField
HStack(spacing: 10) {
processTitle
Spacer(minLength: 0)
searchField.frame(maxWidth: wide ? 220 : 180)
}
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
HStack(spacing: 6) {
MetricProgressBar(value: (row.cpu ?? 0) / Double(max(1, logicalCPUCount)), color: Color("MetricCPU"))
.frame(width: 45, height: 6).accessibilityHidden(true)
Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--").frame(maxWidth: .infinity, alignment: .trailing)
}
}.width(105)
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
Table(rows, selection: $selected, sortOrder: $sortOrder) {
TableColumn("PID", sortUsing: ProcessSort(key: .pid)) { row in Text(verbatim: "\(row.id.pid)") }.width(48)
TableColumn("panel.name", sortUsing: ProcessSort(key: .name)) { row in
HStack(spacing: 5) { ProcessIcon(process: row); Text(verbatim: row.name).lineLimit(1) }
}.width(min: 90, ideal: 140, max: 180)
TableColumn("panel.path", sortUsing: ProcessSort(key: .path)) { row in Text(verbatim: row.path ?? "--").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) }.width(min: 150, ideal: 400)
TableColumn("CPU %", sortUsing: ProcessSort(key: .cpu)) { row in
Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--")
.frame(maxWidth: .infinity, alignment: .trailing)
}.width(65)
TableColumn("panel.rss", sortUsing: ProcessSort(key: .memory)) { row in Text(verbatim: row.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--") }.width(85)
TableColumn("panel.threads", sortUsing: ProcessSort(key: .threads)) { row in
HStack { Text(verbatim: row.threads.map(String.init) ?? "--"); if row.restricted { Image(systemName: "lock").accessibilityLabel(Text("panel.restricted")) } }
}.width(65)
}
@@ -71,9 +61,9 @@ struct ProcessTableView: View {
.font(.system(size: 12)).padding(10)
.modifier(CardSurface())
.onAppear { rebuild(retainOrder: false) }
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && (byMemory ? rows.contains { $0.residentBytes != nil } : rows.contains { $0.cpu != nil })) }
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && !rows.isEmpty) }
.onChange(of: search) { _, _ in rebuild(retainOrder: held) }
.onChange(of: byMemory) { _, _ in rebuild(retainOrder: false) }
.onChange(of: sortOrder) { _, _ 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) } }
@@ -90,22 +80,14 @@ struct ProcessTableView: View {
}
}
private var processTitle: some View {
HStack(spacing: 8) {
Label("panel.processes", systemImage: "list.bullet.rectangle").font(PanelStyle.title)
Text(verbatim: "\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)")
.foregroundStyle(.secondary).help(Text("panel.coverage"))
}
Label("panel.processes", systemImage: "list.bullet.rectangle")
.font(PanelStyle.title)
.help(Text("\(Text("panel.processScope"))\n\(Text("panel.coverage"))\n\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)"))
}
private var searchField: some View {
TextField("panel.search", text: $search).textFieldStyle(.roundedBorder).focused($searchFocused)
}
private var sorting: some View {
Picker("panel.sort", selection: $byMemory) {
Text("CPU %").tag(false)
Text("panel.rss").tag(true)
}.labelsHidden().pickerStyle(.segmented).controlSize(.small)
}
private func rebuild(retainOrder: Bool) {
rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, byMemory: byMemory, order: retainOrder ? rows.map(\.id) : [])
rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, sorting: sortOrder, order: retainOrder ? rows.map(\.id) : [])
}
}