Files
Kymo/kymo/Features/MenuBar/ProcessTableView.swift
T

114 lines
6.4 KiB
Swift

import SwiftUI
import AppKit
struct ProcessTableView: View {
let snapshot: ProcessSnapshot?
var wide: Bool = true
@State private var search = ""
@State private var sortOrder = [ProcessSort(key: .cpu)]
@State private var hovering = false
@State private var selected: ProcessIdentity?
@State private var rows: [ProcessMetrics] = []
@State private var departed: ProcessMetrics?
@FocusState private var searchFocused: Bool
private var held: Bool { hovering || selected != nil || !search.isEmpty }
private var selectedRow: ProcessMetrics? { rows.first { $0.id == selected } }
private var exitedSelection: ProcessIdentity? {
guard let selected, snapshot != nil, !rows.contains(where: { $0.id == selected }) else { return nil }
return selected
}
var body: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 10) {
processTitle
Spacer(minLength: 0)
searchField.frame(maxWidth: wide ? 220 : 180)
}
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 }
.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 } }
}
}
.font(.system(size: 12)).padding(10)
.modifier(CardSurface())
.onAppear { rebuild(retainOrder: false) }
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && !rows.isEmpty) }
.onChange(of: search) { _, _ in rebuild(retainOrder: held) }
.onChange(of: sortOrder) { _, _ in rebuild(retainOrder: false) }
.onChange(of: selected) { _, _ in if let row = selectedRow { departed = row } }
.onHover { hovering = $0; if !$0 && !held { rebuild(retainOrder: false) } }
.onChange(of: searchFocused) { _, value in if !value && !held { rebuild(retainOrder: false) } }
.task(id: exitedSelection) {
guard let id = exitedSelection else { return }
do { try await Task.sleep(for: .seconds(3)) } catch { return }
if selected == 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() }
}
}
private var processTitle: some View {
Label("panel.processes", systemImage: "list.bullet.rectangle")
.font(PanelStyle.title)
.help(Text("\(Text("panel.processScope"))\n\(Text("panel.coverage"))\n\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)"))
}
private var searchField: some View {
HStack(spacing: 4) {
TextField("panel.search", text: $search).textFieldStyle(.plain).focused($searchFocused)
if !search.isEmpty {
Button { search = ""; searchFocused = true } label: {
Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.accessibilityLabel(Text("clearSearch", tableName: "Process"))
.help(Text("clearSearch", tableName: "Process"))
}
}
.padding(.horizontal, 7).padding(.vertical, 4)
.background(.background, in: RoundedRectangle(cornerRadius: 5))
.overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.primary.opacity(0.15)))
}
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) : [])
}
}