Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Monitor9// File : App/Sources/Features/ProcessesView.swift10// Description : Process explorer: sortable, searchable table, inspector11// with live history of the selected process, confirmed quit12// actions.13// Module : Features14// Repository : https://git.spboucher.ai/orix-monitor15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AppKit92import ORIXMonitorCore93import SwiftUI9495enum ProcessScope: String, CaseIterable, Identifiable {96 case all, mine, apps, other97 var id: String { rawValue }98}99100/// Table row with non-optional sort keys. Unknown figures sort below every known one.101struct ProcessRow: Identifiable {102 var record: ProcessRecord103 var isApp: Bool104 var id: Int32 { record.pid }105 var name: String { record.name }106 var pid: Int32 { record.pid }107 var cpu: Double { record.cpuPercent ?? -1 }108 var memory: UInt64 { record.memory }109 var threads: Int { record.threads }110 var user: String { record.user }111 var cpuTime: Double { record.cpuTime }112 var power: Double { record.power ?? -1 }113 var started: Date { record.startTime ?? .distantPast }114}115116struct ProcessesView: View {117 @Environment(MonitorModel.self) private var model118 @State private var search = ""119 /// Test instances start on the short "Apps" list: XCUITest snapshots every cell, and a Mac can run thousands of processes.120 @State private var scope: ProcessScope = LaunchOptions.isUITest ? .apps : .mine121 @State private var sort = [KeyPathComparator(\ProcessRow.cpu, order: .reverse)]122 @State private var selection: Int32?123 @State private var showInspector = true124 @State private var pending: (action: MonitorModel.ProcessAction, process: ProcessRecord)?125 @State private var failure: String?126 @State private var history: [LivePoint] = []127 @State private var memoryHistory: [LivePoint] = []128 @State private var historyPID: Int32?129130 private var apps: Set<Int32> { Set(NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular }.map(\.processIdentifier)) }131132 private var rows: [ProcessRow] {133 let appPIDs = apps134 let me = getuid()135 return (model.processes?.processes ?? []).filter { p in136 switch scope {137 case .all: true138 case .mine: p.uid == me139 case .apps: appPIDs.contains(p.pid)140 case .other: p.uid != me141 }142 }143 .filter { search.isEmpty || $0.name.localizedCaseInsensitiveContains(search) || String($0.pid) == search || ($0.path?.localizedCaseInsensitiveContains(search) ?? false) }144 .map { ProcessRow(record: $0, isApp: appPIDs.contains($0.pid)) }145 .sorted(using: sort)146 }147148 var body: some View {149 // GeometryReader accepts whatever width the split view offers. The system inspector did not: with a narrow window its150 // minimum width plus the table's made the split view renegotiate sizes forever, and AppKit aborted the app.151 GeometryReader { proxy in152 HStack(spacing: 0) {153 list154 if showInspector, proxy.size.width >= 640 {155 Divider()156 inspector.frame(width: min(320, proxy.size.width * 0.36))157 }158 }159 }160 .background(ORIX.Palette.canvas)161 .searchable(text: $search, placement: .toolbar, prompt: Text("Name, PID or path"))162 .toolbar {163 ToolbarItem {164 Button { showInspector.toggle() } label: { Label("Inspector", systemImage: "sidebar.trailing") }.help("Show or hide the process inspector")165 }166 }167 .onChange(of: model.processes?.interval) { _, _ in recordHistory() }168 .onChange(of: selection) { _, _ in169 history = []170 memoryHistory = []171 historyPID = selection172 }173 .confirmationDialog(confirmationTitle, isPresented: Binding(get: { pending != nil }, set: { if !$0 { pending = nil } }), titleVisibility: .visible) {174 if let pending {175 Button(pending.action == .quit ? "Quit" : "Force Quit", role: .destructive) {176 if !model.perform(pending.action, on: pending.process) {177 failure = String(format: L("macOS did not allow ORIX Monitor to end “%@”."), pending.process.name)178 }179 self.pending = nil180 }181 Button("Cancel", role: .cancel) { self.pending = nil }182 }183 } message: {184 Text(pending?.action == .forceQuit185 ? "The process ends immediately. Unsaved changes in it are lost."186 : "The process is asked to quit and may save its work first.")187 }188 .alert("Could not end the process", isPresented: Binding(get: { failure != nil }, set: { if !$0 { failure = nil } })) {189 Button("OK", role: .cancel) {}190 } message: { Text(failure ?? "") }191 }192193 private var list: some View {194 let f = model.format195 let rows = rows196 return VStack(spacing: 0) {197 HStack(spacing: ORIX.Space.sm) {198 Picker("Show", selection: $scope) {199 Text("My processes").tag(ProcessScope.mine)200 Text("Apps").tag(ProcessScope.apps)201 Text("Other users").tag(ProcessScope.other)202 Text("All").tag(ProcessScope.all)203 }204 .pickerStyle(.segmented).labelsHidden().fixedSize()205 .accessibilityIdentifier("processes.scope")206 Spacer()207 Text(String(format: L("%1$d shown of %2$d"), rows.count, model.processes?.total ?? 0)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)208 .accessibilityIdentifier("processes.count")209 }210 .padding(.horizontal, ORIX.Space.md).padding(.vertical, ORIX.Space.xs)211 Divider()212 Table(rows, selection: $selection, sortOrder: $sort) {213 TableColumn("Process", value: \.name) { row in214 HStack(spacing: 6) {215 Image(systemName: row.isApp ? "app.fill" : "gearshape").font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)216 Text(row.name).lineLimit(1)217 }218 }219 .width(min: 160, ideal: 240)220 TableColumn("PID", value: \.pid) { Text(String($0.pid)).monospacedDigit() }.width(60)221 TableColumn("CPU", value: \.cpu) { row in Text(row.record.cpuPercent.map { f.percent($0, digits: 1) } ?? "—").monospacedDigit() }.width(70)222 TableColumn("Memory", value: \.memory) { row in Text(row.record.hasStatistics ? f.bytes(row.memory, memory: true) : "—").monospacedDigit() }.width(90)223 TableColumn("Threads", value: \.threads) { row in Text(row.record.hasStatistics ? String(row.threads) : "—").monospacedDigit() }.width(60)224 TableColumn("CPU time", value: \.cpuTime) { row in Text(row.record.hasStatistics ? f.clock(row.cpuTime) : "—").monospacedDigit() }.width(90)225 TableColumn("Power", value: \.power) { row in Text(row.record.power.map { "\(f.number($0, digits: 2)) W" } ?? "—").monospacedDigit() }.width(70)226 TableColumn("User", value: \.user) { Text(model.mask($0.user)) }.width(min: 70, ideal: 110)227 TableColumn("Started", value: \.started) { row in228 if let start = row.record.startTime { Text(start, format: .dateTime.month().day().hour().minute()) } else { Text("—") }229 }230 .width(min: 90, ideal: 120)231 }232 .accessibilityIdentifier("processes.table")233 .contextMenu(forSelectionType: Int32.self) { ids in234 if let process = ids.first.flatMap(find) { actions(process) }235 }236 if let restricted = model.processes?.restricted, restricted > 0, scope != .mine, scope != .apps {237 Divider()238 Label(String(format: L("%d processes belong to other users. macOS gives an unprivileged app their identity but not their CPU, memory or start time, so those cells stay empty."), restricted), systemImage: "lock")239 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)240 .padding(.horizontal, ORIX.Space.md).padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .leading)241 }242 }243 .frame(maxWidth: .infinity)244 }245246 private var confirmationTitle: String {247 guard let pending else { return "" }248 return String(format: pending.action == .quit ? L("Quit “%1$@” (PID %2$d)?") : L("Force quit “%1$@” (PID %2$d)?"), pending.process.name, pending.process.pid)249 }250251 private func find(_ pid: Int32) -> ProcessRecord? { model.processes?.processes.first { $0.pid == pid } }252253 /// Keeps a short live history for the selected process only; nothing is stored for the others.254 private func recordHistory() {255 guard let pid = selection, pid == historyPID, let process = find(pid), process.hasStatistics, let date = model.snapshot?.date else { return }256 if let cpu = process.cpuPercent { history.append(LivePoint(date: date, value: cpu)) }257 memoryHistory.append(LivePoint(date: date, value: Double(process.memory)))258 if history.count > 120 { history.removeFirst() }259 if memoryHistory.count > 120 { memoryHistory.removeFirst() }260 }261262 @ViewBuilder private func actions(_ process: ProcessRecord) -> some View {263 if let path = process.path {264 Button("Reveal in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) }265 }266 if let app = NSRunningApplication(processIdentifier: process.pid), app.activationPolicy == .regular {267 Button("Bring to Front") { app.activate() }268 }269 Button("Copy PID") {270 NSPasteboard.general.clearContents()271 NSPasteboard.general.setString(String(process.pid), forType: .string)272 }273 if process.uid == getuid(), process.pid != getpid() {274 Divider()275 Button("Quit…") { pending = (.quit, process) }276 Button("Force Quit…", role: .destructive) { pending = (.forceQuit, process) }277 }278 }279280 @ViewBuilder private var inspector: some View {281 let f = model.format282 if let pid = selection, let p = find(pid) {283 ScrollView {284 VStack(alignment: .leading, spacing: ORIX.Space.sm) {285 Text(p.name).font(.system(size: 16, weight: .bold)).textSelection(.enabled)286 Text("PID \(String(p.pid)) · \(L("parent")) \(String(p.parentPID))" + (find(p.parentPID).map { " (\($0.name))" } ?? "")).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)287 if p.hasStatistics {288 Card("CPU", family: .cpu) {289 Readout(value: p.cpuPercent.map { f.percent($0, digits: 1) } ?? "—", caption: "of one core", size: 22)290 Sparkline(values: history.map(\.value), color: ORIX.Palette.accent).frame(height: 44)291 }292 Card("Memory", family: .memory) {293 Readout(value: f.bytes(p.memory, memory: true), caption: "physical footprint", size: 22)294 Sparkline(values: memoryHistory.map(\.value), color: ORIX.Palette.accentSecondary).frame(height: 44)295 }296 Card("Details") {297 KeyValueRow(L("Threads"), String(p.threads))298 KeyValueRow(L("CPU time"), f.duration(p.cpuTime))299 KeyValueRow(L("Read from disk"), f.bytes(p.diskRead))300 KeyValueRow(L("Written to disk"), f.bytes(p.diskWritten))301 if let power = p.power { KeyValueRow(L("Power (kernel accounting)"), "\(f.number(power, digits: 2)) W") }302 KeyValueRow(L("User"), model.mask(p.user))303 if let start = p.startTime { KeyValueRow(L("Started"), f.date(start)) }304 }305 } else {306 Card("Restricted") {307 Label("Owned by another user", systemImage: "lock").font(.system(size: 12, weight: .medium))308 Text("macOS does not give an unprivileged app the CPU, memory or start time of this process. ORIX Monitor shows nothing rather than a zero.")309 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)310 KeyValueRow(L("User"), model.mask(p.user))311 }312 }313 Card("Executable") {314 Text(model.settings.privacyMask ? "•••" : model.displayPath(p.path)).font(ORIX.Typeface.mono).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)315 }316 HStack { actions(p) }.buttonStyle(.bordered).controlSize(.small)317 }318 .padding(ORIX.Space.md)319 }320 .background(ORIX.Palette.canvas)321 } else {322 ContentUnavailableView("No process selected", systemImage: "list.bullet.rectangle", description: Text("Select a row to inspect it."))323 }324 }325}326