perf(menubar): 减少进程表刷新排序并清理闲置代码
This commit is contained in:
@@ -65,7 +65,7 @@ MetricText 用等宽数字直接显示当前读数。连续追加时 NativePanel
|
||||
|
||||
设置使用 NeutralTabPicker 静态 AppKit 按钮组,保留 tabGroup / tabButton 语义、选中值与键盘导航。
|
||||
|
||||
进程列表使用 view-based NSTableView,只创建可见单元格并原地更新。ProcessTableProjection 负责搜索、排序及悬停 / 选择 / 搜索期间的顺序保持。选择由完整 ProcessIdentity 同步,原生委托回调之后才写回 SwiftUI。只显示 PID、名称、CPU、内存、CPU 功率、线程数六列;使用 plain 样式消除额外行内缩进,由原生滚动宿主在 tile 时按可用宽度分配六列,禁用横向滚动及手动扩宽。路径保留在模型中用于搜索与右键复制。原可见口径 / 能量覆盖说明行移至进程标题提示,保留状态且不占行高。ProcessIconCache 保存 30×30 像素缩略图,最多 128 项 / 1 MiB,30 秒过期、LRU 淘汰、内存压力清空,无轮询任务。
|
||||
进程列表使用 view-based NSTableView,只创建可见单元格并原地更新。ProcessTableProjection 负责搜索、排序及悬停 / 选择 / 搜索期间的顺序保持。保持顺序时按上一轮显示的完整进程身份取回最新行,仅对新出现的匹配行排序后追加。选择由完整 ProcessIdentity 同步,原生委托回调之后才写回 SwiftUI。只显示 PID、名称、CPU、内存、CPU 功率、线程数六列;使用 plain 样式消除额外行内缩进,由原生滚动宿主在 tile 时按可用宽度分配六列,禁用横向滚动及手动扩宽。路径保留在模型中用于搜索与右键复制。原可见口径 / 能量覆盖说明行移至进程标题提示,保留状态且不占行高。ProcessIconCache 保存 30×30 像素缩略图,最多 128 项 / 1 MiB,30 秒过期、LRU 淘汰、内存压力清空,无轮询任务。
|
||||
|
||||
外观、语言、菜单栏勾选和采样配置写入 UserDefaults;固定、暂停、保持唤醒与进程交互不持久化。旧减弱动画偏好键忽略但不清除。AppLanguageScope 传递应用语言并刷新宿主,AppLocalization 为原生菜单取文案;编号风扇保留参数化 Text。
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,25 @@ import Foundation
|
||||
let sorted = ProcessTableProjection.rows([row, high, low, zero], query: "", sorting: [ProcessSort(key: .power, order: direction)], order: [])
|
||||
precondition(sorted.last?.cpuPower == nil && sorted.first?.cpuPower == (direction == .forward ? 0 : 3))
|
||||
}
|
||||
// The selected process can exit while its PID is reused. The replacement
|
||||
// joins the sorted newcomers, while retained rows keep fresh measurements.
|
||||
let fresh = ProcessMetrics(id: large.id, name: large.name, path: nil, cpu: 1,
|
||||
footprintBytes: nil, threads: 2, restricted: false)
|
||||
let newcomer = ProcessMetrics(id: .init(pid: 44, seconds: 10, microseconds: 0),
|
||||
name: "new", path: nil, cpu: 2, footprintBytes: nil,
|
||||
threads: 1, restricted: false)
|
||||
let held = ProcessTableProjection.rows([replacement, newcomer, fresh], query: "",
|
||||
sorting: [ProcessSort(key: .cpu)], order: [id, large.id])
|
||||
precondition(held.map(\.id) == [large.id, newcomer.id, reused])
|
||||
precondition(held.first?.threads == 2 && held.first?.footprintBytes == nil)
|
||||
let filteredHeld = ProcessTableProjection.rows([row, fresh], query: "large", sorting: [], order: [id, large.id])
|
||||
precondition(filteredHeld.map(\.id) == [large.id])
|
||||
|
||||
let nearlyMax = ProcessMetrics(id: id, name: "a", path: nil, cpu: nil,
|
||||
footprintBytes: UInt64.max - 1, threads: nil, restricted: false)
|
||||
let max = ProcessMetrics(id: large.id, name: "z", path: nil, cpu: nil,
|
||||
footprintBytes: UInt64.max, threads: nil, restricted: false)
|
||||
precondition(ProcessSort(key: .memory).compare(nearlyMax, max) == .orderedDescending)
|
||||
print("PASS: filtered/live selection, absent selection/snapshot, failed enumeration, actual exit and PID reuse")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,16 +8,6 @@ import Foundation
|
||||
precondition(ProcessMonitor.cpu(current: 1, previous: 0, elapsed: 0) == nil)
|
||||
precondition(GPUMonitor.normalized(53) == 0.53)
|
||||
precondition(GPUMonitor.normalized(101) == nil && GPUMonitor.normalized(.nan) == nil)
|
||||
let processRows = [
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 1, seconds: 1, microseconds: 1), name: "unknown", path: nil, cpu: nil, footprintBytes: nil, threads: nil, restricted: true),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 2, seconds: 1, microseconds: 2), name: "busy", path: nil, cpu: 2.5, footprintBytes: nil, threads: nil, restricted: false),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 3, seconds: 1, microseconds: 3), name: "idle", path: nil, cpu: 0, footprintBytes: nil, threads: nil, restricted: false),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 4, seconds: 1, microseconds: 4), name: "invalid", path: nil, cpu: -.infinity, footprintBytes: nil, threads: nil, restricted: false)
|
||||
]
|
||||
let processSnapshot = ProcessSnapshot(date: Date(), enumerated: 4, readable: 3, rows: processRows, failed: false)
|
||||
precondition(processSnapshot.highestCPUProcess?.name == "busy")
|
||||
precondition(processSnapshot.highestCPUProcesses(limit: 3).map(\.name) == ["busy", "idle"])
|
||||
precondition(processSnapshot.highestCPUProcesses(limit: 0).isEmpty)
|
||||
var snapshot = MetricsSnapshot()
|
||||
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 1, sent: 1, download: 12, upload: 8),
|
||||
NetworkInterfaceMetrics(name: "utun0", received: 1, sent: 1, download: 99, upload: 99)]
|
||||
|
||||
Reference in New Issue
Block a user