perf(menubar): 减少进程表刷新排序并清理闲置代码

This commit is contained in:
2026-11-16 00:06:14 +08:00
parent 97c1bc3b7f
commit 3ee6b45eb4
7 changed files with 43 additions and 73 deletions
-18
View File
@@ -30,24 +30,6 @@ nonisolated struct ProcessSnapshot: Sendable {
let failed: Bool
}
nonisolated extension ProcessSnapshot {
func highestCPUProcesses(limit: Int) -> [ProcessMetrics] {
guard limit > 0 else { return [] }
var result: [ProcessMetrics] = []
for row in rows {
guard let cpu = row.cpu, cpu.isFinite, cpu >= 0 else { continue }
let index = result.firstIndex { ($0.cpu ?? 0) < cpu } ?? result.endIndex
result.insert(row, at: index)
if result.count > limit { result.removeLast() }
}
return result
}
var highestCPUProcess: ProcessMetrics? {
highestCPUProcesses(limit: 1).first
}
}
nonisolated struct ProcessMemoryRequest: Codable, Sendable {
let token: UUID
let identities: [ProcessIdentity]
@@ -133,7 +133,7 @@ import SwiftUI
}
}
let descriptors = (pendingSorting ?? value.sorting).map {
NSSortDescriptor(key: Self.name($0.key), ascending: $0.order == .forward)
NSSortDescriptor(key: $0.key.rawValue, ascending: $0.order == .forward)
}
if table.sortDescriptors != descriptors { table.sortDescriptors = descriptors }
let oldCount = table.numberOfRows, newCount = value.rows.count
@@ -211,7 +211,7 @@ import SwiftUI
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard !applying else { return }
let order = tableView.sortDescriptors.compactMap { descriptor -> ProcessSort? in
guard let key = Self.key(descriptor.key ?? "") else { return nil }
guard let key = ProcessSort.Key(rawValue: descriptor.key ?? "") else { return nil }
return ProcessSort(key: key, order: descriptor.ascending ? .forward : .reverse)
}
sortRevision += 1; let revision = sortRevision
@@ -237,12 +237,6 @@ import SwiftUI
guard let value = item.representedObject as? String else { return }
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"; 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; case "power": .power; default: nil }
}
}
final class Cell: NSTableCellView {
@@ -10,29 +10,37 @@ nonisolated enum ProcessTableProjection {
}
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 matches = query.isEmpty ? input : input.filter {
$0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query)
|| ($0.path?.localizedCaseInsensitiveContains(query) ?? false)
}
func precedes(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> Bool {
for comparator in sorting {
let result = comparator.compare($0, $1)
let result = comparator.compare(lhs, rhs)
if result != .orderedSame { return result == .orderedAscending }
}
return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name
return lhs.name == rhs.name ? lhs.id.pid < rhs.id.pid : lhs.name < rhs.name
}
guard !order.isEmpty else { return matches.sorted(by: precedes) }
// A snapshot has one row per process identity. Refresh retained rows in their
// displayed order, then apply the active sort only to newly visible processes.
var remaining = Dictionary(uniqueKeysWithValues: matches.lazy.map { ($0.id, $0) })
var result = order.compactMap { remaining.removeValue(forKey: $0) }
result.append(contentsOf: remaining.values.sorted(by: precedes))
return result
}
}
/// 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, power }
enum Key: String { case pid, name, path, cpu, memory, threads, power }
let key: Key
var order: SortOrder = .reverse
func compare(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> ComparisonResult {
func metric(_ a: Double?, _ b: Double?) -> ComparisonResult {
func metric<T: Comparable>(_ a: T?, _ b: T?) -> ComparisonResult {
switch (a, b) {
case (nil, nil): return .orderedSame
case (nil, _): return .orderedDescending
@@ -41,13 +49,13 @@ nonisolated struct ProcessSort: SortComparator, Equatable {
}
}
switch key {
case .pid: return metric(Double(lhs.id.pid), Double(rhs.id.pid))
case .pid: return metric(lhs.id.pid, 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.footprintBytes.map { Double($0) }, rhs.footprintBytes.map { Double($0) })
case .memory: return metric(lhs.footprintBytes, rhs.footprintBytes)
case .power: return metric(lhs.cpuPower, rhs.cpuPower)
case .threads: return metric(lhs.threads.map { Double($0) }, rhs.threads.map { Double($0) })
case .threads: return metric(lhs.threads, rhs.threads)
}
}
@@ -1,23 +0,0 @@
import SwiftUI
/// Clips both layers to the track, including fills narrower than the track height.
struct MetricProgressBar: View {
let value: Double
let color: Color
var cornerRadius: CGFloat? = nil
private var fraction: Double { value.isFinite ? min(1, max(0, value)) : 0 }
var body: some View {
GeometryReader { proxy in
let shape = RoundedRectangle(cornerRadius: cornerRadius ?? proxy.size.height / 2, style: .continuous)
ZStack(alignment: .leading) {
shape.fill(color.opacity(0.15))
shape.fill(color).frame(width: proxy.size.width * fraction)
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(shape)
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}
}