perf(menubar): 降低绘制驻留并复用原生进程表与缩略图

This commit is contained in:
2026-11-04 10:39:15 +08:00
parent 1c26fc18f3
commit 065c53622a
28 changed files with 964 additions and 160 deletions
+1 -4
View File
@@ -88,10 +88,7 @@ struct CPUCoreGrid: View {
return GeometryReader { proxy in
let diameter = min(maximumDiameter, max(0, proxy.size.width - 4))
ZStack {
Circle().inset(by: 1).stroke(color(kind).opacity(0.16), lineWidth: 2)
Circle().inset(by: 1).trim(from: 0, to: value)
.stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round))
.rotationEffect(.degrees(-90))
NativeMetricRing(value: value, color: color(kind), lineWidth: 2, trackOpacity: 0.16, inset: 1)
Text(verbatim: "\(Int((value * 100).rounded()))")
.font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4)
}
@@ -25,6 +25,7 @@ import Observation
private let menuTitle: (String) -> String
private let openSettings: () -> Void
private var showingStatusMenu = false
private var isHiding = false
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
menuTitle: @escaping (String) -> String = { $0 },
@@ -33,7 +34,12 @@ import Observation
self.visibility = visibility
self.menuTitle = menuTitle
self.openSettings = openSettings
self.content = { NSHostingView(rootView: content($0)) }
self.content = {
let host = NSHostingView(rootView: content($0))
// The controller owns the fixed panel frame; content must not negotiate window limits.
host.sizingOptions = []
return host
}
super.init()
panel.title = "Kymo"
panel.isReleasedWhenClosed = false
@@ -126,12 +132,16 @@ import Observation
}
func hide() {
guard !isHiding else { return }
isHiding = true
defer { isHiding = false }
presentation.isOpen = false
panel.orderOut(nil)
#if DEBUG || KYMO_AUDIT
if let content = panel.contentView { lastHiddenContent = content }
#endif
panel.contentView = nil
panel.closeAfterDetachingContent()
visibility(false)
removeMonitors()
}
@@ -197,6 +207,7 @@ final class MonitoringPanel: NSPanel {
var dismiss: (() -> Void)?
override var canBecomeKey: Bool { true }
override var canBecomeMain: Bool { false }
func closeAfterDetachingContent() { super.close() }
override func cancelOperation(_ sender: Any?) { dismiss?() }
override func close() { dismiss?() }
override func performClose(_ sender: Any?) { dismiss?() }
+1 -1
View File
@@ -183,7 +183,7 @@ struct MenuPanelView: View {
}
.buttonStyle(PanelControlButtonStyle())
.padding(4)
.glassEffect(.regular, in: .capsule)
.background(.primary.opacity(0.04), in: .capsule)
}
.controlSize(.small)
.padding(.horizontal, 2).padding(.vertical, 0)
@@ -0,0 +1,240 @@
import AppKit
import SwiftUI
/// Native reusable cells keep process refreshes out of SwiftUI's per-cell render graphs.
@MainActor struct NativeProcessTable: NSViewRepresentable {
let rows: [ProcessMetrics]
@Binding var selection: ProcessIdentity?
@Binding var sorting: [ProcessSort]
let locale: Locale
var onExit: () -> Void = {}
func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSScrollView, context: Context) -> CGSize? {
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true
scroll.autohidesScrollers = true; scroll.drawsBackground = false
let table = ProcessNSTableView()
table.style = .inset; table.rowHeight = 20
table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear
table.allowsMultipleSelection = false; table.allowsEmptySelection = true
table.columnAutoresizingStyle = .sequentialColumnAutoresizingStyle
for (key, width) in [("pid", 48.0), ("name", 140), ("path", 400), ("cpu", 65), ("memory", 85), ("threads", 65)] {
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(key))
column.width = width
column.minWidth = key == "path" ? 150 : key == "name" ? 90 : width
column.maxWidth = key == "name" ? 180 : key == "path" ? 10_000 : width
column.resizingMask = key == "path" ? [.autoresizingMask, .userResizingMask] : .userResizingMask
column.sortDescriptorPrototype = NSSortDescriptor(key: key, ascending: false)
table.addTableColumn(column)
}
table.dataSource = context.coordinator; table.delegate = context.coordinator
table.cancel = { [weak coordinator = context.coordinator] in
Task { @MainActor in coordinator?.parent.onExit() }
}
table.contextMenu = { [weak coordinator = context.coordinator] row in coordinator?.menu(row: row) }
scroll.documentView = table
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let table = scroll.documentView as? NSTableView else { return }
context.coordinator.apply(self, to: table)
}
final class ProcessNSTableView: NSTableView {
var contextMenu: ((Int) -> NSMenu?)?
var cancel: (() -> Void)?
override func keyDown(with event: NSEvent) {
// NSTableView otherwise consumes Esc for its own selection/editing behavior.
if event.keyCode == 53 && event.modifierFlags.intersection([.command, .control, .option, .shift]).isEmpty {
cancelOperation(nil)
} else { super.keyDown(with: event) }
}
override func cancelOperation(_ sender: Any?) {
if let cancel { cancel() } else { super.cancelOperation(sender) }
}
override func menu(for event: NSEvent) -> NSMenu? {
let row = row(at: convert(event.locationInWindow, from: nil))
if row >= 0 { selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) }
return contextMenu?(row)
}
}
@MainActor final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
private(set) var parent: NativeProcessTable
private var applying = false
private var selected: ProcessIdentity?
private var lastAppliedSelection: ProcessIdentity?
private var selectionRevision = 0
private var sortRevision = 0
private var pendingSelection = false
private var pendingSorting: [ProcessSort]?
private var localizedLocale: String?
private var restrictedTitle = ""
private static let placeholder = NSImage(systemSymbolName: "app.dashed", accessibilityDescription: nil)
private(set) var createdCells = 0
init(_ parent: NativeProcessTable) { self.parent = parent; self.selected = parent.selection; self.lastAppliedSelection = parent.selection }
func apply(_ value: NativeProcessTable, to table: NSTableView) {
// An explicit SwiftUI action (e.g. Esc) takes precedence over queued native events.
if value.selection != lastAppliedSelection {
selectionRevision += 1; pendingSelection = false
}
lastAppliedSelection = value.selection
parent = value
applying = true
defer { applying = false }
if !pendingSelection { selected = value.selection }
if localizedLocale != value.locale.identifier {
localizedLocale = value.locale.identifier
restrictedTitle = AppLocalization.string("panel.restricted", locale: value.locale)
for column in table.tableColumns {
let key = column.identifier.rawValue
let title: String
switch key {
case "pid": title = "PID"
case "cpu": title = "CPU %"
case "memory": title = AppLocalization.string("panel.rss", locale: value.locale)
default: title = AppLocalization.string("panel." + key, locale: value.locale)
}
if column.title != title { column.title = title }
}
}
let descriptors = (pendingSorting ?? value.sorting).map {
NSSortDescriptor(key: Self.name($0.key), ascending: $0.order == .forward)
}
if table.sortDescriptors != descriptors { table.sortDescriptors = descriptors }
let oldCount = table.numberOfRows, newCount = value.rows.count
if oldCount != newCount {
table.beginUpdates()
if newCount > oldCount { table.insertRows(at: IndexSet(integersIn: oldCount..<newCount), withAnimation: []) }
else { table.removeRows(at: IndexSet(integersIn: newCount..<oldCount), withAnimation: []) }
table.endUpdates()
}
let selectedIndex = selected.flatMap { id in value.rows.firstIndex { $0.id == id } }
let indices = selectedIndex.map { IndexSet(integer: $0) } ?? []
if table.selectedRowIndexes != indices { table.selectRowIndexes(indices, byExtendingSelection: false) }
let visible = table.rows(in: table.visibleRect)
if visible.location != NSNotFound && visible.length > 0 {
for row in visible.location..<min(newCount, visible.location + visible.length) {
for column in table.tableColumns.indices {
if let cell = table.view(atColumn: column, row: row, makeIfNecessary: false) as? Cell {
update(cell, key: table.tableColumns[column].identifier.rawValue, process: value.rows[row])
}
}
}
}
}
func numberOfRows(in tableView: NSTableView) -> Int { parent.rows.count }
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let column = tableColumn, parent.rows.indices.contains(row) else { return nil }
let key = column.identifier.rawValue
let cell: Cell
if let reused = tableView.makeView(withIdentifier: column.identifier, owner: nil) as? Cell { cell = reused }
else { cell = Cell(key: key); cell.identifier = column.identifier; createdCells += 1 }
update(cell, key: key, process: parent.rows[row])
return cell
}
private func update(_ cell: Cell, key: String, process: ProcessMetrics) {
let text: String
switch key {
case "pid": text = String(process.id.pid)
case "name": text = process.name
case "path": text = process.path ?? "--"
case "cpu": text = process.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--"
case "memory": text = process.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--"
default: text = process.threads.map(String.init) ?? "--"
}
if cell.textField?.stringValue != text { cell.textField?.stringValue = text }
if key == "name" {
let image = PanelResourceAudit.omitted == "icons" ? nil : process.path.flatMap { ProcessIconCache.shared.image(for: $0) }
let desired = image ?? Self.placeholder
if cell.imageView?.image !== desired { cell.imageView?.image = desired }
} else if key == "threads" {
if cell.imageView?.isHidden != !process.restricted { cell.imageView?.isHidden = !process.restricted }
if cell.imageView?.accessibilityLabel() != restrictedTitle { cell.imageView?.setAccessibilityLabel(restrictedTitle) }
}
}
func tableViewSelectionDidChange(_ notification: Notification) {
guard !applying, let table = notification.object as? NSTableView else { return }
selected = parent.rows.indices.contains(table.selectedRow) ? parent.rows[table.selectedRow].id : nil
selectionRevision += 1
let revision = selectionRevision, id = selected
pendingSelection = true
// Never mutate the SwiftUI host while AppKit is inside its delegate callback.
Task { @MainActor [weak self] in
guard let self, self.selectionRevision == revision else { return }
self.pendingSelection = false
if self.parent.selection != id { self.parent.selection = id }
}
}
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 }
return ProcessSort(key: key, order: descriptor.ascending ? .forward : .reverse)
}
sortRevision += 1; let revision = sortRevision
pendingSorting = order
Task { @MainActor [weak self] in
guard let self, self.sortRevision == revision else { return }
self.pendingSorting = nil
if self.parent.sorting != order { self.parent.sorting = order }
}
}
func menu(row: Int) -> NSMenu? {
guard parent.rows.indices.contains(row) else { return nil }
let process = parent.rows[row], menu = NSMenu()
menu.autoenablesItems = false
for (key, value) in [("copyPID", String(process.id.pid)), ("copyName", process.name), ("copyPath", process.path)] {
let item = NSMenuItem(title: AppLocalization.string(key, locale: parent.locale, table: "Process"), action: #selector(copyValue(_:)), keyEquivalent: "")
item.target = self; item.representedObject = value; item.isEnabled = value != nil
menu.addItem(item)
}
return menu
}
@objc private func copyValue(_ item: NSMenuItem) {
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" }
}
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; default: nil }
}
}
final class Cell: NSTableCellView {
private let key: String
init(key: String) {
self.key = key
super.init(frame: .zero)
let text = NSTextField(labelWithString: "")
text.font = ["pid", "cpu", "memory", "threads"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11)
text.alignment = ["cpu", "memory", "threads"].contains(key) ? .right : .left
text.lineBreakMode = .byTruncatingMiddle
text.textColor = key == "path" ? .secondaryLabelColor : .labelColor
addSubview(text); textField = text
if key == "name" || key == "threads" {
let image = NSImageView(); image.imageScaling = .scaleProportionallyDown
if key == "threads" { image.image = NSImage(systemSymbolName: "lock", accessibilityDescription: nil) }
else { image.setAccessibilityElement(false) }
addSubview(image); imageView = image
}
}
required init?(coder: NSCoder) { nil }
override func layout() {
super.layout()
let start: CGFloat = key == "name" ? 22 : 3
let end: CGFloat = key == "threads" ? 16 : 3
textField?.frame = NSRect(x: start, y: max(0, (bounds.height - 16) / 2), width: max(0, bounds.width - start - end), height: 16)
imageView?.frame = key == "name" ? NSRect(x: 2, y: (bounds.height - 15) / 2, width: 15, height: 15) : NSRect(x: bounds.width - 12, y: (bounds.height - 11) / 2, width: 11, height: 11)
}
}
}
+11 -1
View File
@@ -17,10 +17,20 @@ import AppKit
NSApp.terminate(nil)
return
}
@MainActor func plots(in view: NSView?) -> [NativePanelCurve.PlotView] {
guard let view else { return [] }
let own = (view as? NativePanelCurve.PlotView).map { [$0] } ?? []
return own + view.subviews.flatMap { plots(in: $0) }
}
@MainActor func mark(_ event: String) {
var report = metrics.snapshot
report.processes = metrics.processSnapshot
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil)
let views = plots(in: controller.panel.contentView)
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil,
windowNumber: controller.panel.isVisible ? controller.panel.windowNumber : nil,
hoveredPlots: views.filter { $0.input?.hoveredIndex != nil }.count, nativePlots: views.count,
pointerInsidePanel: controller.panel.isVisible && controller.panel.frame.contains(NSEvent.mouseLocation),
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] })
}
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
+1 -4
View File
@@ -20,10 +20,7 @@ struct ProcessIcon: View {
guard PanelResourceAudit.omitted != "icons" else { return }
// 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)
icon = ProcessIconCache.shared.image(for: path)
}
}
}
@@ -0,0 +1,67 @@
import AppKit
/// Cache only display-sized pixels; never retain Workspace's original icon representations.
@MainActor final class ProcessIconCache {
static let shared = ProcessIconCache(observePressure: true)
static let pixelLimit = 1_048_576
private struct Entry {
let image: NSImage
let expires: TimeInterval
let cost: Int
var access: UInt64
}
private var entries: [String: Entry] = [:]
private var access: UInt64 = 0
private let resolve: (String) -> NSImage
private let clock: () -> TimeInterval
private var pressure: DispatchSourceMemoryPressure?
private(set) var pixelBytes = 0
var count: Int { entries.count }
init(observePressure: Bool = false, resolve: @escaping (String) -> NSImage = { NSWorkspace.shared.icon(forFile: $0) },
clock: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
self.resolve = resolve; self.clock = clock
if observePressure {
let source = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: .main)
source.setEventHandler { [weak self] in Task { @MainActor in self?.removeAll() } }
source.resume(); pressure = source
}
}
deinit { pressure?.cancel() }
func image(for path: String) -> NSImage? {
let url = URL(fileURLWithPath: path)
let owner = sequence(first: url, next: { $0.path == "/" ? nil : $0.deletingLastPathComponent() })
.first { $0.pathExtension == "app" }?.path ?? path
let now = clock()
access &+= 1
if var entry = entries[owner], now < entry.expires {
entry.access = access; entries[owner] = entry
return entry.image
}
if let old = entries.removeValue(forKey: owner) { pixelBytes -= old.cost }
guard let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 30, pixelsHigh: 30,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0),
let context = NSGraphicsContext(bitmapImageRep: bitmap) else { return nil }
let original = resolve(owner)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = context
context.imageInterpolation = .high
original.draw(in: NSRect(x: 0, y: 0, width: 30, height: 30), from: .zero, operation: .copy, fraction: 1)
NSGraphicsContext.restoreGraphicsState()
bitmap.size = NSSize(width: 15, height: 15)
let image = NSImage(size: bitmap.size); image.addRepresentation(bitmap)
let cost = bitmap.bytesPerRow * bitmap.pixelsHigh
guard cost <= Self.pixelLimit else { return nil }
entries[owner] = Entry(image: image, expires: now + 30, cost: cost, access: access)
pixelBytes += cost
while entries.count > 128 || pixelBytes > Self.pixelLimit {
guard let oldest = entries.min(by: { $0.value.access < $1.value.access })?.key,
let removed = entries.removeValue(forKey: oldest) else { break }
pixelBytes -= removed.cost
}
return image
}
func removeAll() { entries.removeAll(); pixelBytes = 0 }
}
+8 -38
View File
@@ -28,34 +28,7 @@ struct ProcessTableView: View {
}
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, 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)
}
.contextMenu(forSelectionType: ProcessIdentity.self) { identities in
if let id = identities.first, let row = rows.first(where: { $0.id == id }) {
Button { copy(String(row.id.pid)) } label: { Text("copyPID", tableName: "Process") }
Button { copy(row.name) } label: { Text("copyName", tableName: "Process") }
Button { if let path = row.path { copy(path) } } label: { Text("copyPath", tableName: "Process") }
.disabled(row.path == nil)
}
}
.font(.system(size: 11)).monospacedDigit()
.tableStyle(.inset(alternatesRowBackgrounds: true))
.scrollContentBackground(.hidden)
.transaction { $0.animation = nil }
NativeProcessTable(rows: rows, selection: $selected, sorting: $sortOrder, locale: locale, onExit: handleExit)
.overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } }
if exitedSelection != nil, let departed {
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { selected = nil; self.departed = nil } }
@@ -75,12 +48,13 @@ struct ProcessTableView: View {
do { try await Task.sleep(for: .seconds(3)) } catch { return }
if exitedSelection == 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() }
}
.onExitCommand(perform: handleExit)
}
private func handleExit() {
if !search.isEmpty { search = "" }
else if selected != nil { selected = nil; departed = nil }
else if searchFocused { searchFocused = false }
else { NSApp.keyWindow?.close() }
}
private var processTitle: some View {
Label("panel.processes", systemImage: "list.bullet.rectangle")
@@ -91,10 +65,6 @@ struct ProcessTableView: View {
placeholder: AppLocalization.string("panel.search", locale: locale))
}
private func copy(_ value: String) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(value, forType: .string)
}
private func rebuild(retainOrder: Bool) {
rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, sorting: sortOrder, order: retainOrder ? rows.map(\.id) : [])
}