import AppKit import SwiftUI import Observation @MainActor @Observable private final class State { var rows: [ProcessMetrics] var selection: ProcessIdentity? var sorting = [ProcessSort(key: .cpu)] var locale = Locale(identifier: "en") var insideDelegate = false var exits = 0 init() { rows = (0..<500).map { index in ProcessMetrics(id: ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0), name: "worker-\(index)", path: nil, cpu: Double(index) / 100, residentBytes: 10_000_000, threads: 2, restricted: true) } } } private struct Host: View { let state: State var body: some View { NativeProcessTable(rows: state.rows, selection: Binding(get: { state.selection }, set: { precondition(!state.insideDelegate, "Selection published inside an AppKit delegate callback") state.selection = $0 }), sorting: Binding(get: { state.sorting }, set: { precondition(!state.insideDelegate, "Sort published inside an AppKit delegate callback") state.sorting = $0 }), locale: state.locale, onExit: { state.exits += 1 }).frame(maxWidth: .infinity, maxHeight: .infinity) } } @MainActor private final class DelegateProbe: NSObject, NSTableViewDelegate { let state: State let target: NativeProcessTable.Coordinator init(_ state: State, _ target: NativeProcessTable.Coordinator) { self.state = state; self.target = target } func tableViewSelectionDidChange(_ notification: Notification) { state.insideDelegate = true target.tableViewSelectionDidChange(notification) state.insideDelegate = false } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { state.insideDelegate = true target.tableView(tableView, sortDescriptorsDidChange: oldDescriptors) state.insideDelegate = false } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { target.tableView(tableView, viewFor: tableColumn, row: row) } } @main struct NativeProcessTableChecks { @MainActor static func main() { _ = NSApplication.shared; NSApp.setActivationPolicy(.accessory) Task { @MainActor in let state = State() let window = NSWindow(contentRect: NSRect(x: 30, y: 30, width: 900, height: 260), styleMask: [.titled], backing: .buffered, defer: false) window.isReleasedWhenClosed = false let host = NSHostingView(rootView: Host(state: state)) window.contentView = host; window.makeKeyAndOrderFront(nil) try? await Task.sleep(for: .milliseconds(200)) let table = find(host)! let coordinator = table.delegate as! NativeProcessTable.Coordinator let probe = DelegateProbe(state, coordinator) table.delegate = probe precondition(table.numberOfRows == 500 && table.tableColumns.count == 6) precondition(table.frame.width >= table.enclosingScrollView!.contentSize.width - 1, "Native table must fill its viewport") precondition(coordinator.createdCells > 0 && coordinator.createdCells < 200, "Rows must be virtualized") let chosen = state.rows[10].id table.selectRowIndexes(IndexSet(integer: 10), byExtendingSelection: false) precondition(state.selection == nil, "Native selection must be deferred") await until { state.selection == chosen } state.rows.reverse() await until { table.selectedRow == 489 } precondition(state.selection == chosen, "Selection must follow identity after reordering") for index in 0..<12 { state.rows[0] = ProcessMetrics(id: state.rows[0].id, name: "updated-\(index)", path: nil, cpu: Double(index), residentBytes: nil, threads: nil, restricted: false) try? await Task.sleep(for: .milliseconds(20)) } let visible = table.rows(in: table.visibleRect) if visible.location != NSNotFound, visible.length > 0, let cell = table.view(atColumn: 1, row: visible.location, makeIfNecessary: false) as? NSTableCellView { precondition(cell.textField?.stringValue == state.rows[visible.location].name) } else { preconditionFailure("No visible native cell") } precondition(coordinator.createdCells < 250, "Refreshes must reuse visible cells") table.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] await until { state.sorting == [ProcessSort(key: .name, order: .forward)] } let menu = coordinator.menu(row: 0)! precondition(menu.items.count == 3 && menu.items[0].representedObject as? String == String(state.rows[0].id.pid)) precondition(menu.items[1].representedObject as? String == state.rows[0].name && !menu.items[2].isEnabled) state.rows.removeAll { $0.id == chosen } await until { table.numberOfRows == 499 && table.selectedRow == -1 } precondition(state.selection == chosen, "Filtering/removal must not invent a new selected identity") state.selection = nil state.locale = Locale(identifier: "zh-Hans") await until { table.tableColumns[1].title == "名称" } state.rows.removeAll(); await until { table.numberOfRows == 0 } precondition(window.makeFirstResponder(table)) let escape = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)! window.sendEvent(escape) await until { state.exits == 1 } window.orderOut(nil); window.close() print("PASS: real native table virtualization/reuse, deferred delegate writes, identity selection, sorting, copy menu, missing paths, removal, locale and in-window Esc event routing") fflush(stdout); NSApp.terminate(nil) } NSApp.run() } @MainActor private static func until(_ predicate: () -> Bool, line: UInt = #line) async { let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while !predicate() && ContinuousClock.now < deadline { try? await Task.sleep(for: .milliseconds(20)) } precondition(predicate(), "Timed out waiting for native table update at line \(line)") } @MainActor private static func find(_ view: NSView) -> NSTableView? { if let table = view as? NSTableView { return table } for child in view.subviews { if let table = find(child) { return table } } return nil } }