59 lines
3.0 KiB
Swift
59 lines
3.0 KiB
Swift
import Foundation
|
|
|
|
/// Compute once per data/filter/sort event, never from row rendering or scroll position.
|
|
nonisolated enum ProcessTableProjection {
|
|
/// Filtering hides rows without terminating processes. A failed read proves no departure.
|
|
static func exitedSelection(_ selected: ProcessIdentity?, in snapshot: ProcessSnapshot?) -> ProcessIdentity? {
|
|
guard let selected, let snapshot, !snapshot.failed,
|
|
!snapshot.rows.contains(where: { $0.id == selected }) else { return nil }
|
|
return selected
|
|
}
|
|
|
|
static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], order: [ProcessIdentity]) -> [ProcessMetrics] {
|
|
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
|
|
return input.filter {
|
|
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false)
|
|
}.sorted {
|
|
let aRank = ranks[$0.id] ?? Int.max, bRank = ranks[$1.id] ?? Int.max
|
|
if aRank != bRank { return aRank < bRank }
|
|
for comparator in sorting {
|
|
let result = comparator.compare($0, $1)
|
|
if result != .orderedSame { return result == .orderedAscending }
|
|
}
|
|
return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Missing metrics stay last in either direction. Every newly selected column starts descending.
|
|
nonisolated struct ProcessSort: SortComparator, Equatable {
|
|
enum Key { case pid, name, path, cpu, memory, threads, power }
|
|
let key: Key
|
|
var order: SortOrder = .reverse
|
|
|
|
func compare(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> ComparisonResult {
|
|
func metric(_ a: Double?, _ b: Double?) -> ComparisonResult {
|
|
switch (a, b) {
|
|
case (nil, nil): return .orderedSame
|
|
case (nil, _): return .orderedDescending
|
|
case (_, nil): return .orderedAscending
|
|
case let (a?, b?): return directed(a < b ? .orderedAscending : a > b ? .orderedDescending : .orderedSame)
|
|
}
|
|
}
|
|
switch key {
|
|
case .pid: return metric(Double(lhs.id.pid), Double(rhs.id.pid))
|
|
case .name: return directed(lhs.name.localizedStandardCompare(rhs.name))
|
|
case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? ""))
|
|
case .cpu: return metric(lhs.cpu, rhs.cpu)
|
|
case .memory: return metric(lhs.footprintBytes.map { Double($0) }, rhs.footprintBytes.map { Double($0) })
|
|
case .power: return metric(lhs.cpuPower, rhs.cpuPower)
|
|
case .threads: return metric(lhs.threads.map { Double($0) }, rhs.threads.map { Double($0) })
|
|
}
|
|
}
|
|
|
|
private func directed(_ value: ComparisonResult) -> ComparisonResult {
|
|
guard order == .reverse else { return value }
|
|
return value == .orderedAscending ? .orderedDescending : value == .orderedDescending ? .orderedAscending : .orderedSame
|
|
}
|
|
}
|