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.. 0 { for row in visible.location.. 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.footprintBytes.map { String(format: "%.1f MB", Double($0) / 1_048_576) } ?? "--" 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) } } }