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
+6
View File
@@ -227,3 +227,9 @@ CPU、GPU、电池在三列及窄屏网格中共享显式行高:基础 260pt
`ResourceCard` 由布局器确定尺寸,GeometryReader 将外壳背景与描边绑定最终分配 bounds,内层标题固定 20pt,详情统一在独立内容栈中布局;温度/规格胶囊均为 10pt medium、16pt 高。六卡绘图区统一 58pt;存储物理 I/O 范围保留为趋势图帮助说明。内存/存储共用分布标题、8pt 容量条、10pt 分类字段和 32pt 底部字段。电池缺失与内存缺失保留趋势/首分隔线,详情显示状态。进程区使用相同外壳及标题样式,原生控件行为保留。 `ResourceCard` 由布局器确定尺寸,GeometryReader 将外壳背景与描边绑定最终分配 bounds,内层标题固定 20pt,详情统一在独立内容栈中布局;温度/规格胶囊均为 10pt medium、16pt 高。六卡绘图区统一 58pt;存储物理 I/O 范围保留为趋势图帮助说明。内存/存储共用分布标题、8pt 容量条、10pt 分类字段和 32pt 底部字段。电池缺失与内存缺失保留趋势/首分隔线,详情显示状态。进程区使用相同外壳及标题样式,原生控件行为保留。
MenuPanelView 主文件保留生命周期、布局和顶栏控制,资源卡片与网络装配分别收敛到同名扩展文件,仍属 Features/MenuBar;跨文件仅开放装配所需的内部状态/计算属性,没有新增公共 API。删除旧的未使用行高公式和展示辅助函数,测试覆盖视图实际调用的布局策略。此节与前述布局现状替代历史记录中的 239/240/260pt 行高、GPU 42pt 统计区等旧描述;当前 GPU 统计区为 46pt。采样、XPC、Core 数据流及设置架构未改。 MenuPanelView 主文件保留生命周期、布局和顶栏控制,资源卡片与网络装配分别收敛到同名扩展文件,仍属 Features/MenuBar;跨文件仅开放装配所需的内部状态/计算属性,没有新增公共 API。删除旧的未使用行高公式和展示辅助函数,测试覆盖视图实际调用的布局策略。此节与前述布局现状替代历史记录中的 239/240/260pt 行高、GPU 42pt 统计区等旧描述;当前 GPU 统计区为 46pt。采样、XPC、Core 数据流及设置架构未改。
### 进程表表头排序与图标(2026-11-03)
`ProcessTableView` 使用原生 Table 的 sortOrder 绑定,`ProcessSort`/`ProcessTableProjection` 在排序、筛选或快照事件时计算行序,不在单元格渲染时排序;初始 CPU 降序,数值缺失在任意方向均置后。交互期间保序,主动切换表头立即重新投影。标题覆盖率移入悬停说明,右侧只保留搜索;CPU 仅显示百分比数值,不按逻辑核心数归一化为条形图。没有逐进程 GPU 列或数据接入。
`ProcessIcon` 属于 MenuBar 特性层,由进程列表与电池进程行复用,通过采样路径解析应用包或可执行文件图标;无路径使用占位。图标任务以进程身份和路径为键,UI 渲染时不查询 PID 对应应用,Core 数据模型保持不依赖 AppKit。
+8
View File
@@ -195,3 +195,11 @@
- 本地化文件原有修改保留,不纳入本次提交;部分过长英文标签采用省略与帮助提示,未通过任意缩小普通字号腾空间。 - 本地化文件原有修改保留,不纳入本次提交;部分过长英文标签采用省略与帮助提示,未通过任意缩小普通字号腾空间。
验证证据与未覆盖矩阵见 [UI 规范改造验证记录](ui-consistency-validation.md)。原截图微差未通过原版本完整运行时重建定位到单一根因;本轮修正了标题固有高度、背景 bounds 与行高分配契约,并用本轮视图测量验证结果,不能倒推旧版本的唯一原因。 验证证据与未覆盖矩阵见 [UI 规范改造验证记录](ui-consistency-validation.md)。原截图微差未通过原版本完整运行时重建定位到单一根因;本轮修正了标题固有高度、背景 bounds 与行高分配契约,并用本轮视图测量验证结果,不能倒推旧版本的唯一原因。
## 9. 进程板块专项调整(2026-11-03)
标题原数字为“详细指标可读进程数 / 枚举总数 · 筛选后行数”。这些数字作为覆盖率诊断信息保留在标题悬停说明,标题区只显示名称,右侧只保留搜索框。移除独立排序选择器和恢复排序按钮;排序入口统一到原生 Table 表头,初始 CPU 降序,新选择列默认降序,再次点击切换方向。PID、名称、路径、CPU、内存、线程支持排序,缺失数值始终置后;悬停、选中或搜索时继续保序,主动点击表头立即重排。
CPU 列移除进度条,保留一位小数数值。进程名称增加 15pt 图标,按采样可执行文件路径寻找最近的 `.app` 图标,无应用包时使用文件图标,路径不可读时使用占位图标。共用 `ProcessIcon`,同步替换电池进程行的重复实现,避免依赖可能复用的 PID 获取应用图标。按用户后续要求取消 GPU 列,不增加 GPU 采样或占位列。
验证:Debug 构建及独立布局/进程投影检查通过;新增升降序、PID 排序和缺失指标置后边界检查。独立原生窗口加载实际 ProcessTableView,固定三行数据验证初始 CPU 降序、点击内存默认降序、CPU 表头再次点击切换升序、缺失数据末尾、搜索和 Escape 恢复;截图确认应用图标和纯数值 CPU。该窗口不加载正式菜单面板生命周期;正式菜单形态、窄窗口横向滚动及长期图标加载成本本轮未验证。原生交互测试时有临时 GPU 占位列,随后按用户要求移除;最终无 GPU 版本通过构建和投影检查,并重新启动隔离窗口确认列已移除、默认 CPU 降序正常。
@@ -269,7 +269,6 @@ extension MenuPanelView {
struct EnergyProcessListRow: View { struct EnergyProcessListRow: View {
let process: ProcessMetrics let process: ProcessMetrics
@State private var icon: NSImage?
private var progress: Double { private var progress: Double {
guard let value = process.cpu, value.isFinite else { return 0 } guard let value = process.cpu, value.isFinite else { return 0 }
@@ -278,15 +277,7 @@ struct EnergyProcessListRow: View {
var body: some View { var body: some View {
HStack(spacing: 5) { HStack(spacing: 5) {
Group { ProcessIcon(process: process)
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)
Text(verbatim: process.name).lineLimit(1).truncationMode(.middle) Text(verbatim: process.name).lineLimit(1).truncationMode(.middle)
.frame(width: 66, alignment: .leading) .frame(width: 66, alignment: .leading)
GeometryReader { proxy in GeometryReader { proxy in
@@ -306,11 +297,6 @@ struct EnergyProcessListRow: View {
} }
.font(PanelStyle.label) .font(PanelStyle.label)
.frame(height: 16) .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 resourceRows
} }
if metrics.isPanelVisible { 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) .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. /// Compute once per data/filter/sort event, never from row rendering or scroll position.
nonisolated enum ProcessTableProjection { 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) }) let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
return input.filter { return input.filter {
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false) query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false)
}.sorted { }.sorted {
let aRank = ranks[$0.id] ?? Int.max, bRank = ranks[$1.id] ?? Int.max let aRank = ranks[$0.id] ?? Int.max, bRank = ranks[$1.id] ?? Int.max
if aRank != bRank { return aRank < bRank } if aRank != bRank { return aRank < bRank }
let a = byMemory ? $0.residentBytes.map(Double.init) ?? -1 : $0.cpu ?? -1 for comparator in sorting {
let b = byMemory ? $1.residentBytes.map(Double.init) ?? -1 : $1.cpu ?? -1 let result = comparator.compare($0, $1)
if a != b { return a > b } if result != .orderedSame { return result == .orderedAscending }
}
return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name 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
}
}
+20 -38
View File
@@ -4,9 +4,8 @@ import AppKit
struct ProcessTableView: View { struct ProcessTableView: View {
let snapshot: ProcessSnapshot? let snapshot: ProcessSnapshot?
var wide: Bool = true var wide: Bool = true
var logicalCPUCount: Int = 1
@State private var search = "" @State private var search = ""
@State private var byMemory = false @State private var sortOrder = [ProcessSort(key: .cpu)]
@State private var hovering = false @State private var hovering = false
@State private var selected: ProcessIdentity? @State private var selected: ProcessIdentity?
@State private var rows: [ProcessMetrics] = [] @State private var rows: [ProcessMetrics] = []
@@ -22,35 +21,26 @@ struct ProcessTableView: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 6) { VStack(alignment: .leading, spacing: 6) {
if wide {
HStack(spacing: 10) { HStack(spacing: 10) {
processTitle processTitle
Image(systemName: "info.circle").foregroundStyle(.secondary).help(Text("panel.processScope"))
Spacer(minLength: 0) Spacer(minLength: 0)
if held { Button { selected = nil; rebuild(retainOrder: false) } label: { Image(systemName: "arrow.up.arrow.down") }.help(Text("panel.liveSort")) } searchField.frame(maxWidth: wide ? 220 : 180)
searchField.frame(width: 220)
sorting.frame(width: 160)
}
} else {
HStack { processTitle; Spacer(); sorting.frame(width: 140) }
searchField
} }
if snapshot?.failed == true { Text("panel.processFailed") } if snapshot?.failed == true { Text("panel.processFailed") }
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) } else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
// Native Table owns its vertical/horizontal scrolling and recycles visible cells. // Native Table owns its vertical/horizontal scrolling and recycles visible cells.
Table(rows, selection: $selected) { Table(rows, selection: $selected, sortOrder: $sortOrder) {
TableColumn("PID") { row in Text(verbatim: "\(row.id.pid)") }.width(48) TableColumn("PID", sortUsing: ProcessSort(key: .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.name", sortUsing: ProcessSort(key: .name)) { row in
TableColumn("panel.path") { row in Text(verbatim: row.path ?? "--").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) }.width(min: 150, ideal: 400) HStack(spacing: 5) { ProcessIcon(process: row); Text(verbatim: row.name).lineLimit(1) }
TableColumn("CPU %") { row in }.width(min: 90, ideal: 140, max: 180)
HStack(spacing: 6) { TableColumn("panel.path", sortUsing: ProcessSort(key: .path)) { row in Text(verbatim: row.path ?? "--").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) }.width(min: 150, ideal: 400)
MetricProgressBar(value: (row.cpu ?? 0) / Double(max(1, logicalCPUCount)), color: Color("MetricCPU")) TableColumn("CPU %", sortUsing: ProcessSort(key: .cpu)) { row in
.frame(width: 45, height: 6).accessibilityHidden(true) Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--")
Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--").frame(maxWidth: .infinity, alignment: .trailing) .frame(maxWidth: .infinity, alignment: .trailing)
} }.width(65)
}.width(105) 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.rss") { 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
TableColumn("panel.threads") { row in
HStack { Text(verbatim: row.threads.map(String.init) ?? "--"); if row.restricted { Image(systemName: "lock").accessibilityLabel(Text("panel.restricted")) } } HStack { Text(verbatim: row.threads.map(String.init) ?? "--"); if row.restricted { Image(systemName: "lock").accessibilityLabel(Text("panel.restricted")) } }
}.width(65) }.width(65)
} }
@@ -71,9 +61,9 @@ struct ProcessTableView: View {
.font(.system(size: 12)).padding(10) .font(.system(size: 12)).padding(10)
.modifier(CardSurface()) .modifier(CardSurface())
.onAppear { rebuild(retainOrder: false) } .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: 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 } } .onChange(of: selected) { _, _ in if let row = selectedRow { departed = row } }
.onHover { hovering = $0; if !$0 && !held { rebuild(retainOrder: false) } } .onHover { hovering = $0; if !$0 && !held { rebuild(retainOrder: false) } }
.onChange(of: searchFocused) { _, value in if !value && !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 { private var processTitle: some View {
HStack(spacing: 8) { Label("panel.processes", systemImage: "list.bullet.rectangle")
Label("panel.processes", systemImage: "list.bullet.rectangle").font(PanelStyle.title) .font(PanelStyle.title)
Text(verbatim: "\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)") .help(Text("\(Text("panel.processScope"))\n\(Text("panel.coverage"))\n\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)"))
.foregroundStyle(.secondary).help(Text("panel.coverage"))
}
} }
private var searchField: some View { private var searchField: some View {
TextField("panel.search", text: $search).textFieldStyle(.roundedBorder).focused($searchFocused) 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) { 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) : [])
} }
} }
+17 -5
View File
@@ -34,15 +34,27 @@ import CoreGraphics
return ProcessMetrics(id: id, name: "worker-\(index)", return ProcessMetrics(id: id, name: "worker-\(index)",
path: path, cpu: Double(index), residentBytes: UInt64(2000 - index), threads: 1, restricted: false) path: path, cpu: Double(index), residentBytes: UInt64(2000 - index), threads: 1, restricted: false)
} }
let cpu = ProcessTableProjection.rows(input, query: "", byMemory: false, order: []) let cpu = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .cpu)], order: [])
precondition(cpu.first?.id.pid == 2000 && cpu.count == 2000) precondition(cpu.first?.id.pid == 2000 && cpu.count == 2000)
let memory = ProcessTableProjection.rows(input, query: "", byMemory: true, order: []) let memory = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .memory)], order: [])
precondition(memory.first?.id.pid == 1) precondition(memory.first?.id.pid == 1)
let held = ProcessTableProjection.rows(input, query: "", byMemory: true, order: cpu.map(\.id)) let held = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .memory)], order: cpu.map(\.id))
precondition(held.map(\.id) == cpu.map(\.id)) precondition(held.map(\.id) == cpu.map(\.id))
let matched = ProcessTableProjection.rows(input, query: "needle", byMemory: false, order: []) let matched = ProcessTableProjection.rows(input, query: "needle", sorting: [ProcessSort(key: .cpu)], order: [])
precondition(matched.count == 1 && matched[0].id.pid == 43) precondition(matched.count == 1 && matched[0].id.pid == 43)
precondition(ProcessTableProjection.rows(input, query: "does-not-exist", byMemory: false, order: []).isEmpty) precondition(ProcessTableProjection.rows(input, query: "does-not-exist", sorting: [ProcessSort(key: .cpu)], order: []).isEmpty)
let ascending = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .cpu, order: .forward)], order: [])
precondition(ascending.first?.id.pid == 1)
let missing = ProcessMetrics(id: ProcessIdentity(pid: 3000, seconds: 1, microseconds: 0), name: "missing", path: nil,
cpu: nil, residentBytes: nil, threads: nil, restricted: true)
for direction in [SortOrder.forward, .reverse] {
for key in [ProcessSort.Key.cpu, .memory, .threads] {
let result = ProcessTableProjection.rows(input + [missing], query: "", sorting: [ProcessSort(key: key, order: direction)], order: [])
precondition(result.last?.id == missing.id)
}
}
let pidSorted = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .pid)], order: [])
precondition(pidSorted.first?.id.pid == 2000)
print("PASS: physical-row heights, column breakpoints, width conservation, resource scrolling, visible-frame bounds/chrome/negative origins, 2000-row CPU/RSS projection, frozen order, path search and empty results") print("PASS: physical-row heights, column breakpoints, width conservation, resource scrolling, visible-frame bounds/chrome/negative origins, 2000-row CPU/RSS projection, frozen order, path search and empty results")
} }
} }