Files
Kymo/kymo/Features/MenuBar/NativeProcessTable.swift

270 lines
15 KiB
Swift

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 = FittingScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = false
scroll.horizontalScrollElasticity = .none
scroll.autohidesScrollers = true; scroll.drawsBackground = false
let table = ProcessNSTableView()
table.style = .plain; table.rowHeight = 20
table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear
table.allowsMultipleSelection = false; table.allowsEmptySelection = true
table.columnAutoresizingStyle = .noColumnAutoresizing
table.intercellSpacing.width = 0
for (key, width) in [("pid", 48.0), ("name", 140), ("cpu", 65), ("memory", 85), ("power", 90), ("threads", 65)] {
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(key))
column.width = width
column.minWidth = 0
column.maxWidth = 10_000
column.resizingMask = []
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)
}
private final class FittingScrollView: NSScrollView {
private var fitting = false
override func tile() {
super.tile()
guard !fitting, let table = documentView as? ProcessNSTableView else { return }
fitting = true; defer { fitting = false }
table.fitColumns(to: contentView.bounds.width)
}
}
final class ProcessNSTableView: NSTableView {
/// Allocate the complete viewport; AppKit's uniform resizing can leave columns clipped at narrow widths.
func fitColumns(to width: CGFloat) {
guard width.isFinite, width > 0, tableColumns.count == 6 else { return }
let minimum: [CGFloat] = [32,54,40,52,54,32]
let preferred: [CGFloat] = [48,140,65,85,90,65]
let minimumTotal = minimum.reduce(0, +)
let baseScale = min(1, width / minimumTotal)
let extraScale = max(0, width - minimumTotal) / (preferred.reduce(0, +) - minimumTotal)
for index in tableColumns.indices {
let value = minimum[index] * baseScale + (preferred[index] - minimum[index]) * extraScale
if abs(tableColumns[index].width - value) > 0.01 { tableColumns[index].width = value }
}
if abs(frame.width - width) > 0.01 { setFrameSize(CGSize(width: width, height: frame.height)) }
}
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: $0.key.rawValue, 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 "cpu": text = process.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--"
case "memory": text = process.footprintBytes.map { String(format: "%.1f MB", Double($0) / 1_048_576) } ?? "--"
case "power": text = process.formattedPower
default: text = process.threads.map(String.init) ?? "--"
}
if cell.textField?.stringValue != text { cell.textField?.stringValue = text }
if key == "power" {
let help = AppLocalization.string("energy.scopeHelp", locale: parent.locale)
let window = process.powerWindow.map {
String(format: AppLocalization.string("energy.window %@", locale: parent.locale), String(format: "%.1f", $0))
}
let tooltip = window.map { help + "\n" + $0 } ?? help
if cell.toolTip != tooltip { cell.toolTip = tooltip }
}
if key == "name" {
let image = 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 = ProcessSort.Key(rawValue: 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)
}
}
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", "power"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11)
text.alignment = ["cpu", "memory", "threads", "power"].contains(key) ? .right : .left
text.lineBreakMode = .byTruncatingMiddle
text.textColor = .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)
}
}
}