Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions App/Dashboard/CPUSection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ struct CPUDetails: View {
let history: History<CPULoad>
let frequencies: FrequencySample?
let temperature: Temperature?
let processes: TopProcesses?
let processes: TopApps?

@Environment(\.temperatureUnit) private var temperatureUnit

Expand Down Expand Up @@ -54,7 +54,7 @@ struct CPUDetails: View {
)
}
}
ProcessList.byCPU(processes, tint: DashboardSection.cpu.tint)
AppList.byCPU(processes, tint: DashboardSection.cpu.tint)
}
}

Expand Down
57 changes: 38 additions & 19 deletions App/Dashboard/DashboardComponents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -434,31 +434,31 @@ extension RateChart where Element == NetworkSample {
}
}

/// The busiest few processes by one measure, with bars relative to the busiest.
/// The busiest few apps by one measure, with bars relative to the busiest.
/// Shows placeholder rows until the first usage arrives, so the details don't jump.
struct ProcessList: View {
struct AppList: View {
let title: String
let processes: [ProcessUsage]?
let apps: [AppUsage]?
let tint: Color
let measure: (ProcessUsage) -> Double
let value: (ProcessUsage) -> String
let measure: (AppUsage) -> Double
let value: (AppUsage) -> String

var body: some View {
VStack(alignment: .leading, spacing: 4) {
DetailsHeading(title)
if let processes {
let top = processes.map(measure).max() ?? 0
ForEach(processes) { process in
row(name: process.name, fraction: top > 0 ? measure(process) / top : 0, value: value(process))
if let apps {
let top = apps.map(measure).max() ?? 0
ForEach(apps) { usage in
row(app: usage.app, fraction: top > 0 ? measure(usage) / top : 0, value: value(usage))
}
if processes.isEmpty {
Text("No processes to show")
if apps.isEmpty {
Text("No apps to show")
.font(.caption)
.foregroundStyle(.secondary)
}
} else {
ForEach(0..<4, id: \.self) { _ in
row(name: "Process name", fraction: 0, value: "0.0%")
row(app: AppIdentity(name: "App name", bundleURL: nil), fraction: 0, value: "0.0%")
}
.redacted(reason: .placeholder)
}
Expand All @@ -468,25 +468,44 @@ struct ProcessList: View {
}
}

private func row(name: String, fraction: Double, value: String) -> some View {
private func row(app: AppIdentity, fraction: Double, value: String) -> some View {
HStack(spacing: 8) {
Text(name)
Image(nsImage: AppIcons.icon(for: app.bundleURL))
.resizable()
.frame(width: 16, height: 16)
Text(app.name)
.lineLimit(1)
.truncationMode(.middle)
.frame(maxWidth: .infinity, alignment: .leading)
ProgressBar(fraction: fraction, color: tint)
.frame(width: 60)
Text(value)
.monospacedDigit()
.lineLimit(1)
.frame(width: 64, alignment: .trailing)
}
.font(.callout)
.accessibilityElement(children: .ignore)
.accessibilityLabel(name)
.accessibilityLabel(app.name)
.accessibilityValue(value)
}
}

/// App icons, cached since the lists redraw on every reading.
@MainActor
private enum AppIcons {
private static var cache: [URL: NSImage] = [:]
private static let executable = NSWorkspace.shared.icon(for: .unixExecutable)

/// The generic executable icon for processes outside an app.
static func icon(for bundleURL: URL?) -> NSImage {
guard let bundleURL else { return executable }
if let icon = cache[bundleURL] { return icon }
let icon = NSWorkspace.shared.icon(forFile: bundleURL.path(percentEncoded: false))
cache[bundleURL] = icon
return icon
}
}

extension Power {
/// Milliwatts below a watt, so idle processes don't all read "0.0 W".
var processFormatted: String {
Expand Down Expand Up @@ -584,9 +603,9 @@ func summary(_ parts: String?...) -> String? {
/// Shown in place of a reading that isn't available.
let missingValue = "—"

extension ProcessList {
static func byCPU(_ processes: TopProcesses?, title: String = "Top processes", tint: Color) -> some View {
ProcessList(title: title, processes: processes?.byCPU, tint: tint, measure: \.cpu.cores) { $0.cpu.formatted() }
extension AppList {
static func byCPU(_ processes: TopApps?, title: String = "Top apps", tint: Color) -> some View {
AppList(title: title, apps: processes?.byCPU, tint: tint, measure: \.cpu.cores) { $0.cpu.formatted() }
.padding(.top, 4)
}
}
4 changes: 2 additions & 2 deletions App/Dashboard/GPUSection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct GPUDetails: View {
let frequency: Frequency?
let maximumFrequency: Frequency?
let totalMemory: ByteCount?
let processes: TopProcesses?
let processes: TopApps?

@Environment(\.temperatureUnit) private var temperatureUnit

Expand All @@ -51,7 +51,7 @@ struct GPUDetails: View {
)
}
// macOS doesn't expose GPU time per process without root, so this shows CPU use instead.
ProcessList.byCPU(processes, title: "Top processes by CPU", tint: DashboardSection.gpu.tint)
AppList.byCPU(processes, title: "Top apps by CPU", tint: DashboardSection.gpu.tint)
}
}

Expand Down
10 changes: 5 additions & 5 deletions App/Dashboard/MemorySection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ struct MemorySection: View {
struct MemoryDetails: View {
let memory: MemorySample
let history: History<Percent>
let processes: TopProcesses?
let processes: TopApps?

var body: some View {
VStack(alignment: .leading, spacing: 6) {
Expand All @@ -54,12 +54,12 @@ struct MemoryDetails: View {
if let swap = memory.swapUsed {
DetailRow(label: "Swap used", value: swap.bytes == 0 ? "None" : swap.formatted(.memory))
}
ProcessList(
title: "Top processes",
processes: processes?.byMemory,
AppList(
title: "Top apps",
apps: processes?.byMemory,
tint: DashboardSection.memory.tint,
measure: { Double($0.memory.bytes) },
value: { $0.memory.formatted(.memory) }
value: { $0.memory.formattedCompact() }
)
.padding(.top, 4)
}
Expand Down
6 changes: 3 additions & 3 deletions App/Dashboard/PowerSection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ struct PowerDetails: View {
let sensors: SensorSample?
let battery: BatterySample?
let history: History<Power>
let processes: TopProcesses?
let processes: TopApps?
let isKeepingAwake: Bool

@Environment(\.temperatureUnit) private var temperatureUnit
Expand Down Expand Up @@ -70,9 +70,9 @@ struct PowerDetails: View {
value: fan.isSpinning ? "\(fan.rpm.formatted(.number.precision(.fractionLength(0)))) RPM" : "Off"
)
}
ProcessList(
AppList(
title: "Top energy use",
processes: processes?.byPower,
apps: processes?.byPower,
tint: DashboardSection.power.tint,
measure: \.power.watts,
value: \.power.processFormatted
Expand Down
7 changes: 4 additions & 3 deletions PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ made by Wolff.Tech.
## What the app reads

Barometry reads CPU, GPU, memory, disk, network, sensor, and battery
statistics from macOS, and the names and resource usage of running processes
for the dashboard's top-process lists. These readings stay in memory for the
graphs and history and are never written to disk or sent anywhere.
statistics from macOS. For the dashboard's top-app lists, it also reads the
resource usage of running processes and the names of the apps responsible
for them. These readings stay in memory for the graphs and history and are
never written to disk or sent anywhere.

## What the app controls

Expand Down
116 changes: 83 additions & 33 deletions Packages/BarometryKit/Sources/BarometryKit/Model/ProcessSample.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,61 @@ public struct CPUUsage: Hashable, Comparable, Sendable {
}
}

/// One process's resource use over the last interval.
public struct ProcessUsage: Equatable, Sendable, Identifiable {
/// The app a group of processes belongs to.
public struct AppIdentity: Equatable, Sendable {
public let name: String
/// The app bundle, for its icon. Nil for processes outside an app, such as command-line tools.
public let bundleURL: URL?

public init(name: String, bundleURL: URL?) {
self.name = name
self.bundleURL = bundleURL
}

/// The outermost app bundle in the path, so helpers nested inside an app, such as
/// "Google Chrome Helper (Renderer).app", name the app itself. Otherwise the file name.
init(executablePath path: String) {
let url = URL(filePath: path)
let components = url.pathComponents
if let index = components.firstIndex(where: { $0.hasSuffix(".app") }) {
let bundle = URL(filePath: NSString.path(withComponents: Array(components[...index])), directoryHint: .isDirectory)
self.init(name: bundle.deletingPathExtension().lastPathComponent, bundleURL: bundle)
} else {
self.init(name: url.lastPathComponent, bundleURL: nil)
}
}
}

/// One app's resource use over the last interval, summed over every process macOS holds it
/// responsible for. That includes helpers outside its bundle, such as Safari's
/// WebContent processes, and command-line tools started from it, as Activity Monitor's
/// Energy tab counts them.
public struct AppUsage: Equatable, Sendable, Identifiable {
/// The responsible process's ID.
public let id: Int32
public internal(set) var name: String
public internal(set) var app: AppIdentity
public let cpu: CPUUsage
/// Physical footprint, as Activity Monitor's "Memory" column.
public let memory: ByteCount
public let power: Power

public init(id: Int32, name: String, cpu: CPUUsage, memory: ByteCount, power: Power) {
public init(id: Int32, app: AppIdentity, cpu: CPUUsage, memory: ByteCount, power: Power) {
self.id = id
self.name = name
self.app = app
self.cpu = cpu
self.memory = memory
self.power = power
}
}

/// The busiest processes by each measure. Only the user's own processes are included,
/// The busiest apps by each measure. Only the user's own processes are included,
/// since reading other users' needs root.
public struct TopProcesses: Equatable, Sendable {
public let byCPU: [ProcessUsage]
public let byMemory: [ProcessUsage]
public let byPower: [ProcessUsage]
public struct TopApps: Equatable, Sendable {
public let byCPU: [AppUsage]
public let byMemory: [AppUsage]
public let byPower: [AppUsage]

public init(byCPU: [ProcessUsage], byMemory: [ProcessUsage], byPower: [ProcessUsage]) {
public init(byCPU: [AppUsage], byMemory: [AppUsage], byPower: [AppUsage]) {
self.byCPU = byCPU
self.byMemory = byMemory
self.byPower = byPower
Expand All @@ -57,6 +86,8 @@ public struct TopProcesses: Equatable, Sendable {
/// Cumulative counters for one process from `proc_pid_rusage`.
struct ProcessReading: Equatable {
let pid: Int32
/// The process macOS holds responsible for this one, which may be itself.
let owner: Int32
/// Tells a reused process ID apart from the process that had it before.
let startTime: UInt64
/// User and system time, in nanoseconds.
Expand All @@ -66,9 +97,9 @@ struct ProcessReading: Equatable {
let memory: UInt64
}

/// Turns successive readings of every process into the busiest few.
/// Turns successive readings of every process into the busiest few apps.
struct ProcessUsageTracker {
/// Processes in each list.
/// Apps in each list.
static let count = 4
/// Shortest span worth measuring. A tick that lands just after the first reading would
/// otherwise rank processes by a few milliseconds of noise.
Expand All @@ -77,13 +108,14 @@ struct ProcessUsageTracker {
private var previous: (readings: [Int32: ProcessReading], time: ContinuousClock.Instant)?

/// Returns nil for the first readings, since usage needs two, and for readings too soon
/// after the last, which are dropped. Only processes present in both readings are ranked.
/// `name` is called only for the processes that make a list.
/// after the last, which are dropped. Only processes present in both readings count.
/// `identify` is called only for the apps that make a list, with the responsible process
/// and one of its processes to fall back on if the responsible one has exited.
mutating func update(
_ readings: [ProcessReading],
at time: ContinuousClock.Instant,
name: (Int32) -> String
) -> TopProcesses? {
identify: (_ owner: Int32, _ member: Int32) -> AppIdentity
) -> TopApps? {
if let previous, time - previous.time < Self.minimumInterval {
return nil
}
Expand All @@ -92,30 +124,48 @@ struct ProcessUsageTracker {
guard let earlier else { return nil }
let elapsed = (time - earlier.time).seconds

// Named later, since looking up a name costs more than reading a process.
let measured = readings.compactMap { reading -> ProcessUsage? in
guard let before = earlier.readings[reading.pid], before.startTime == reading.startTime else { return nil }
return ProcessUsage(
id: reading.pid,
name: "",
cpu: CPUUsage(cores: Double(reading.cpuTime &- before.cpuTime) / 1e9 / elapsed),
memory: ByteCount(bytes: Int64(clamping: reading.memory)),
power: Power(watts: Double(reading.energy &- before.energy) / 1e9 / elapsed)
var totals: [Int32: Totals] = [:]
for reading in readings {
guard let before = earlier.readings[reading.pid], before.startTime == reading.startTime else { continue }
totals[reading.owner, default: Totals(member: reading.pid)].add(reading, since: before)
}
// Identified later, since looking up an app costs more than reading a process.
let measured = totals.map { owner, total in
AppUsage(
id: owner,
app: AppIdentity(name: "", bundleURL: nil),
cpu: CPUUsage(cores: Double(total.cpuTime) / 1e9 / elapsed),
memory: ByteCount(bytes: Int64(clamping: total.memory)),
power: Power(watts: Double(total.energy) / 1e9 / elapsed)
)
}
var names: [Int32: String] = [:]
func top<Value: Comparable>(by value: (ProcessUsage) -> Value) -> [ProcessUsage] {
var apps: [Int32: AppIdentity] = [:]
func top<Value: Comparable>(by value: (AppUsage) -> Value) -> [AppUsage] {
measured.sorted { value($0) > value($1) }.prefix(Self.count).map { usage in
var named = usage
named.name = names[usage.id] ?? name(usage.id)
names[usage.id] = named.name
return named
var identified = usage
identified.app = apps[usage.id] ?? identify(usage.id, totals[usage.id]!.member)
apps[usage.id] = identified.app
return identified
}
}
return TopProcesses(byCPU: top(by: \.cpu), byMemory: top(by: \.memory), byPower: top(by: \.power))
return TopApps(byCPU: top(by: \.cpu), byMemory: top(by: \.memory), byPower: top(by: \.power))
}

mutating func reset() {
previous = nil
}

/// One app's usage since the earlier readings.
private struct Totals {
let member: Int32
var cpuTime: UInt64 = 0
var energy: UInt64 = 0
var memory: UInt64 = 0

mutating func add(_ reading: ProcessReading, since before: ProcessReading) {
cpuTime &+= reading.cpuTime &- before.cpuTime
energy &+= reading.energy &- before.energy
memory &+= reading.memory
}
}
}
Loading
Loading