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
+11 -5
View File
@@ -52,6 +52,7 @@ nonisolated struct NetworkMonitor {
guard getifaddrs(&head) == 0 else { return [:] }
defer { freeifaddrs(head) }
var result: [String: (index: UInt32, addresses: [String], active: Bool)] = [:]
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
var cursor = head
while let entry = cursor {
defer { cursor = entry.pointee.ifa_next }
@@ -60,15 +61,20 @@ nonisolated struct NetworkMonitor {
let active = flags & UInt32(IFF_UP | IFF_RUNNING) == UInt32(IFF_UP | IFF_RUNNING)
var item = result[name] ?? (if_nametoindex(entry.pointee.ifa_name), [], active)
if let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) {
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(address, socklen_t(address.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 {
item.addresses.append(String(cString: host))
if let host = numericAddress(address, buffer: &hostBuffer) {
item.addresses.append(host)
}
}
item.addresses.sort()
result[name] = item
}
return result
return result.mapValues { (index: $0.index, addresses: $0.addresses.sorted(), active: $0.active) }
}
static func numericAddress(_ address: UnsafePointer<sockaddr>, buffer: inout [CChar]) -> String? {
guard !buffer.isEmpty else { return nil }
let capacity = socklen_t(buffer.count)
guard getnameinfo(address, socklen_t(address.pointee.sa_len), &buffer, capacity, nil, 0, NI_NUMERICHOST) == 0 else { return nil }
return String(cString: buffer)
}
/// NET_RT_IFLIST2 exposes 64-bit counters, avoiding getifaddrs' 4 GB wrap.
+6 -1
View File
@@ -21,7 +21,7 @@ nonisolated enum SamplingDiagnostics {
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil) {
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil, windowNumber: Int? = nil, hoveredPlots: Int? = nil, nativePlots: Int? = nil, pointerInsidePanel: Bool? = nil, plotBounds: [[Double]]? = nil) {
guard enabled else { return }
var payload: [String: Any] = [
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
@@ -31,6 +31,11 @@ nonisolated enum SamplingDiagnostics {
"load": snapshot.load
]
payload["hiddenHostAlive"] = hiddenHostAlive
payload["windowNumber"] = windowNumber
payload["hoveredPlots"] = hoveredPlots
payload["nativePlots"] = nativePlots
payload["pointerInsidePanel"] = pointerInsidePanel
payload["plotBounds"] = plotBounds
payload["cpu"] = snapshot.cpu?.usage
payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature
+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) : [])
}
+130
View File
@@ -0,0 +1,130 @@
import AppKit
import SwiftUI
/// A bounded native plot; SwiftUI still owns axes, legends and hover presentation.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, 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 makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap, hoveredIndex: hoveredIndex))
}
struct Input: Equatable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
}
final class PlotView: NSView {
private(set) var input: Input?
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
super.init(frame: .zero)
wantsLayer = true
layerContentsRedrawPolicy = .onSetNeedsDisplay
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard input != value else { return }
input = value
needsDisplay = true
}
override func setFrameSize(_ newSize: NSSize) {
let changed = frame.size != newSize
super.setFrameSize(newSize)
if changed { needsDisplay = true }
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance()
needsDisplay = true
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current?.cgContext else { return }
context.saveGState()
defer { context.restoreGState() }
context.clip(to: bounds)
context.setLineWidth(0.5)
context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.10).cgColor)
for step in 0...10 {
let x = bounds.width * Double(step) / 10
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height))
}
for step in 0...2 {
let y = bounds.height * Double(step) / 2
context.move(to: CGPoint(x: 0, y: y)); context.addLine(to: CGPoint(x: bounds.width, y: y))
}
context.strokePath()
guard let input, let first = input.frame.dates.first, let last = input.frame.dates.last,
!input.colors.isEmpty, !input.scales.isEmpty else { return }
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
for index in input.frame.series.indices {
let tint = NSColor(input.colors[min(index, input.colors.count - 1)])
let proposedScale = input.scales[min(index, input.scales.count - 1)]
let scale = proposedScale.isFinite && proposedScale > 0 ? proposedScale : 1
let runs = PanelCurveGeometry.runs(dates: input.frame.dates, values: input.frame.series[index],
maximumGap: input.maximumGap, boundaryDates: input.frame.boundaryDates, intervals: input.frame.intervals)
context.setFillColor(tint.cgColor)
context.setStrokeColor(tint.cgColor)
context.setLineWidth(1.5)
context.setLineCap(.round); context.setLineJoin(.round)
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) }
guard let start = points.first, let finish = points.last else { continue }
if points.count == 1 {
context.fillEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4))
continue
}
let line = CGMutablePath(); line.move(to: start)
for (a, b) in zip(points, points.dropFirst()) {
let middle = (a.x + b.x) / 2
line.addCurve(to: b, control1: CGPoint(x: middle, y: a.y), control2: CGPoint(x: middle, y: b.y))
}
let area = line.mutableCopy()!
area.addLine(to: CGPoint(x: finish.x, y: bounds.height))
area.addLine(to: CGPoint(x: start.x, y: bounds.height)); area.closeSubpath()
if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB),
colors: [tint.withAlphaComponent(0.20).cgColor, tint.withAlphaComponent(0.01).cgColor] as CFArray,
locations: [0, 1]) {
context.saveGState(); context.addPath(area); context.clip()
context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: bounds.height), options: [])
context.restoreGState()
}
context.addPath(line); context.strokePath()
}
}
if let index = input.hoveredIndex, input.frame.dates.indices.contains(index), last > first {
let x = bounds.width * domain.position(input.frame.dates[index])
context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.45).cgColor)
context.setLineWidth(1); context.setLineDash(phase: 0, lengths: [3, 2])
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height)); context.strokePath()
context.setLineDash(phase: 0, lengths: [])
for series in input.frame.series.indices {
let values = input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let scale = input.scales[min(series, input.scales.count - 1)]
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
context.setFillColor(NSColor(input.colors[min(series, input.colors.count - 1)]).cgColor)
context.fillEllipse(in: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5))
}
}
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
import Foundation
/// A render frame may keep one outgoing point beyond the bounded 60-sample history.
nonisolated struct PanelCurveFrame {
nonisolated struct PanelCurveFrame: Equatable {
let dates: [Date]
let series: [[Double?]]
let intervals: [TimeInterval]
+2 -78
View File
@@ -123,25 +123,9 @@ struct PanelTrendChart: View {
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight)
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale],
maximumGap: max(5, expectedInterval * 2),
targetBegin: dates.first, targetEnd: dates.last,
previousBegin: nil, previousEnd: nil, progress: 1)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
Path { path in
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: proxy.size.height))
}.stroke(.primary.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [3, 2]))
ForEach(0..<4, id: \.self) { series in
let values = [first, second, third, fourth][series]
if index < values.count, let value = values[index], value.isFinite {
let seriesScale = [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale][series]
Circle().fill([color, secondColor, thirdColor, fourthColor][series]).frame(width: 5, height: 5)
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / seriesScale))))
}
}
}
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index)
}
.contentShape(Rectangle())
.onContinuousHover { phase in
@@ -199,63 +183,3 @@ struct PanelTrendChart: View {
.accessibilityElement(children: .combine)
}
}
private struct PanelCurveCanvas: View, Animatable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
let targetBegin: Date?
let targetEnd: Date?
let previousBegin: Date?
let previousEnd: Date?
var progress: CGFloat
var animatableData: CGFloat {
get { progress }
set { progress = newValue }
}
var body: some View {
Canvas { context, size in
var grid = Path()
for step in 0...10 {
let x = size.width * Double(step) / 10
grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: size.height))
}
for step in 0...2 {
let y = size.height * Double(step) / 2
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
}
context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5)
guard let first = targetBegin, let last = targetEnd else { return }
let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd,
begin: first, end: last, progress: Double(progress))
for seriesIndex in frame.series.indices {
let values = frame.series[seriesIndex]
let tint = colors[min(seriesIndex, colors.count - 1)]
let scale = scales[min(seriesIndex, scales.count - 1)]
for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) {
let points = run.map { item in
CGPoint(x: size.width * domain.position(item.date),
y: size.height * (1 - min(1, max(0, item.value / scale))))
}
guard let start = points.first, let finish = points.last else { continue }
var line = Path(); line.move(to: start)
for pair in zip(points, points.dropFirst()) {
let middle = (pair.0.x + pair.1.x) / 2
// Horizontal tangents keep the rounded curve between adjacent sample values.
line.addCurve(to: pair.1, control1: CGPoint(x: middle, y: pair.0.y), control2: CGPoint(x: middle, y: pair.1.y))
}
if points.count == 1 {
context.fill(Path(ellipseIn: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)), with: .color(tint))
} else {
var area = line
area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath()
context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
}
}
}
}
}
}
+2 -5
View File
@@ -11,13 +11,10 @@ struct MetricRingGauge: View {
var body: some View {
VStack(spacing: 3) {
ZStack {
Circle().stroke(color.opacity(0.17), lineWidth: 3)
Circle().trim(from: 0, to: fraction)
.stroke(color, style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotationEffect(.degrees(-90))
NativeMetricRing(value: fraction, color: color, lineWidth: 3, trackOpacity: 0.17, inset: 2)
AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12)
}.padding(2).frame(width: 28, height: 28).accessibilityHidden(true)
}.frame(width: 28, height: 28).accessibilityHidden(true)
Text(title).font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.7)
}
+69
View File
@@ -0,0 +1,69 @@
import AppKit
import SwiftUI
/// Small Core Graphics arcs avoid creating a SwiftUI path-rendering surface for every gauge.
struct NativeMetricRing: NSViewRepresentable {
let value: Double
let color: Color
let lineWidth: CGFloat
let trackOpacity: Double
let inset: CGFloat
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, 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 makeNSView(context: Context) -> RingView { RingView() }
func updateNSView(_ view: RingView, context: Context) {
view.configure(Input(value: value.isFinite ? min(1, max(0, value)) : 0, color: color,
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset))
}
struct Input: Equatable {
let value: Double
let color: Color
let lineWidth: CGFloat
let trackOpacity: Double
let inset: CGFloat
}
final class RingView: NSView {
private(set) var input: Input?
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
super.init(frame: .zero)
wantsLayer = true; layerContentsRedrawPolicy = .onSetNeedsDisplay
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard value != input else { return }
input = value; needsDisplay = true
}
override func setFrameSize(_ newSize: NSSize) {
let changed = newSize != frame.size
super.setFrameSize(newSize)
if changed { needsDisplay = true }
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance(); needsDisplay = true
}
override func draw(_ dirtyRect: NSRect) {
guard let input, let context = NSGraphicsContext.current?.cgContext else { return }
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
guard radius > 0 else { return }
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let tint = NSColor(input.color)
context.saveGState(); defer { context.restoreGState() }
context.setLineWidth(input.lineWidth); context.setLineCap(.round)
context.setStrokeColor(tint.withAlphaComponent(input.trackOpacity).cgColor)
context.strokeEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))
guard input.value > 0 else { return }
context.setStrokeColor(tint.cgColor)
context.addArc(center: center, radius: radius, startAngle: -.pi / 2,
endAngle: -.pi / 2 + 2 * .pi * input.value, clockwise: false)
context.strokePath()
}
}
}