SPB Git

Repository Public License

ComputeViews.swift 22.8 KB 401 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Monitor9// File             : App/Sources/Features/ComputeViews.swift10// Description      : CPU, GPU and memory detail pages.11// Module           : Features12// Repository       : https://git.spboucher.ai/orix-monitor13// Created          : 2026-11-2114// Last Modified    : 2026-11-2115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : Proprietary, all rights reserved (see license file)81// License File     : LICENSE82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import ORIXMonitorCore90import SwiftUI9192// MARK: - CPU9394struct CPUView: View {95    @Environment(MonitorModel.self) private var model96    @Environment(\.colorBlindSafe) private var safe9798    var body: some View {99        let f = model.format100        let color = MetricFamily.cpu.color(colorBlindSafe: safe)101        let cpu = model.snapshot?.cpu102        Page {103            PageHeader(title: "CPU", subtitle: "\(model.system.chip) · " + String(format: L("%d cores"), model.system.topology.physicalCores), family: .cpu)104            CardRow {105                Card("Total", family: .cpu) {106                    Readout(value: cpu.map { f.percent($0.total.busy * 100, digits: 1) } ?? "—", caption: "100 % = every core busy", size: 34)107                    Spacer(minLength: 0)108                    KeyValueRow(L("User"), cpu.map { f.percent($0.total.user * 100, digits: 1) } ?? "—", swatch: color)109                    KeyValueRow(L("System"), cpu.map { f.percent($0.total.system * 100, digits: 1) } ?? "—", swatch: MetricFamily.thermal.color(colorBlindSafe: safe))110                    KeyValueRow(L("Idle"), cpu.map { f.percent($0.total.idle * 100, digits: 1) } ?? "—", swatch: ORIX.Palette.surfaceRaised)111                }112                .frame(minWidth: 220, maxWidth: 300)113                Card("Usage", family: .cpu) {114                    LiveChart(series: [115                        LiveSeries(id: "user", name: L("User"), color: color, points: model.series(.cpuUser)),116                        LiveSeries(id: "system", name: L("System"), color: MetricFamily.thermal.color(colorBlindSafe: safe), points: model.series(.cpuSystem)),117                    ], domain: 0...100, format: { f.percent($0) }, stacked: true)118                }119            }120            CardRow {121                Card("Cores", family: .cpu) {122                    if let cpu {123                        CoreGrid(cores: cpu.cores, color: color)124                    } else {125                        Text("Collecting samples…").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)126                    }127                    if !model.system.topology.groups.isEmpty {128                        Text(model.system.topology.groups.map { String(format: L("%1$d %2$@ cores"), $0.logicalCores, $0.name) }.joined(separator: " · "))129                            .font(.system(size: 12, weight: .medium))130                        Text("macOS reports how many cores each performance level has, not which core number belongs to which level. Cores are therefore shown by number, unlabelled.")131                            .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)132                    }133                }134                Card("Core activity", family: .cpu) {135                    CoreHeatmap(history: model.coreHistory, color: color).frame(minHeight: 150)136                    Text("One row per core, newest sample on the right. Stronger colour means busier.")137                        .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)138                }139            }140            CardRow {141                Card("Load and peaks", family: .cpu) {142                    let window = model.values(.cpuTotal, last: MonitorModel.liveCapacity)143                    KeyValueRow(L("Load average (1, 5, 15 min)"), cpu?.loadAverage.map { f.number($0, digits: 2) }.joined(separator: "   ") ?? "—")144                    KeyValueRow(L("Peak in the live window"), window.max().map { f.percent($0, digits: 1) } ?? "—")145                    KeyValueRow(L("Average in the live window"), window.isEmpty ? "—" : f.percent(window.reduce(0, +) / Double(window.count), digits: 1))146                    KeyValueRow(L("Sampling interval"), model.snapshot.map { "\(f.number($0.interval, digits: 1)) s" } ?? "—")147                    KeyValueRow(L("Measured interval of the last sample"), cpu.map { "\(f.number($0.interval, digits: 2)) s" } ?? "—")148                    UnavailableRow(label: L("CPU frequency"), reason: L("Not published on Apple Silicon."))149                }150                Card("Top processes by CPU", family: .cpu) {151                    ProcessContribution(byMemory: false)152                }153            }154            SourcesCard(metrics: [.cpuTotal, .cpuUser, .cpuSystem, .loadAverage1])155        }156    }157}158159/// Per-core bars with numeric labels.160struct CoreGrid: View {161    var cores: [CPULoad]162    var color: Color163164    var body: some View {165        LazyVGrid(columns: [GridItem(.adaptive(minimum: 58), spacing: 8)], spacing: 8) {166            ForEach(Array(cores.enumerated()), id: \.offset) { index, core in167                VStack(spacing: 3) {168                    ZStack(alignment: .bottom) {169                        RoundedRectangle(cornerRadius: 4).fill(ORIX.Palette.surfaceRaised)170                        RoundedRectangle(cornerRadius: 4).fill(color.opacity(0.35 + 0.65 * core.busy)).frame(height: max(2, 44 * CGFloat(core.busy)))171                    }172                    .frame(height: 44)173                    Text("\(Int((core.busy * 100).rounded())) %").font(ORIX.Typeface.caption)174                    Text("\(index + 1)").font(.system(size: 9)).foregroundStyle(ORIX.Palette.textTertiary)175                }176                .accessibilityElement(children: .ignore)177                .accessibilityLabel(Text("Core \(index + 1)"))178                .accessibilityValue(Text("\(Int((core.busy * 100).rounded())) %"))179            }180        }181    }182}183184/// Core × time heatmap of the live window.185struct CoreHeatmap: View {186    var history: [[Double]]187    var color: Color188189    var body: some View {190        Canvas { context, size in191            guard let cores = history.last?.count, cores > 0, !history.isEmpty else { return }192            let columns = MonitorModel.liveCapacity193            let cellWidth = size.width / CGFloat(columns)194            let cellHeight = size.height / CGFloat(cores)195            let offset = columns - history.count196            for (t, sample) in history.enumerated() where sample.count == cores {197                for (core, busy) in sample.enumerated() {198                    let rect = CGRect(x: CGFloat(offset + t) * cellWidth, y: CGFloat(core) * cellHeight, width: cellWidth + 0.5, height: max(1, cellHeight - 1))199                    context.fill(Path(rect), with: .color(color.opacity(0.06 + 0.94 * min(max(busy, 0), 1))))200                }201            }202        }203        .background(ORIX.Palette.surfaceRaised.opacity(0.4), in: RoundedRectangle(cornerRadius: 6))204        .clipShape(RoundedRectangle(cornerRadius: 6))205        .accessibilityElement(children: .ignore)206        .accessibilityLabel(Text("Core activity"))207        .accessibilityValue(Text(summary))208    }209210    private var summary: String {211        guard let last = history.last, !last.isEmpty else { return L("Collecting samples…") }212        let busiest = last.enumerated().max { $0.element < $1.element }!213        return String(format: L("Busiest core right now: %1$d at %2$d %%"), busiest.offset + 1, Int((busiest.element * 100).rounded()))214    }215}216217/// Horizontal bars showing how much each top process contributes.218struct ProcessContribution: View {219    var byMemory: Bool220    @Environment(MonitorModel.self) private var model221    @Environment(\.colorBlindSafe) private var safe222223    var body: some View {224        let f = model.format225        let all = (model.processes?.processes ?? []).filter { $0.hasStatistics && (byMemory || $0.cpuPercent != nil) }226        let rows = Array(all.sorted { byMemory ? $0.memory > $1.memory : ($0.cpuPercent ?? -1) > ($1.cpuPercent ?? -1) }.prefix(7))227        let top = byMemory ? Double(rows.first?.memory ?? 1) : max(rows.first?.cpuPercent ?? 1, 1)228        let color = (byMemory ? MetricFamily.memory : MetricFamily.cpu).color(colorBlindSafe: safe)229        VStack(alignment: .leading, spacing: 6) {230            ForEach(rows) { p in231                VStack(alignment: .leading, spacing: 2) {232                    HStack {233                        Text(p.name).font(.system(size: 12)).lineLimit(1).truncationMode(.middle)234                        Spacer()235                        Text(byMemory ? f.bytes(p.memory, memory: true) : (p.cpuPercent.map { f.percent($0, digits: 1) } ?? "—")).font(ORIX.Typeface.value)236                    }237                    Meter(fraction: (byMemory ? Double(p.memory) : (p.cpuPercent ?? 0)) / top, color: color, height: 4)238                }239                .accessibilityElement(children: .combine)240            }241            if rows.isEmpty { Text("Collecting samples…").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary) }242            if !byMemory {243                Text("Per-process figures use 100 % = one core, as Activity Monitor does.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)244            }245            if let restricted = model.processes?.restricted, restricted > 0 {246                Text("\(restricted) processes owned by other users report no figures and are not ranked.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)247            }248        }249    }250}251252// MARK: - GPU253254struct GPUView: View {255    @Environment(MonitorModel.self) private var model256    @Environment(\.colorBlindSafe) private var safe257258    var body: some View {259        let f = model.format260        let color = MetricFamily.gpu.color(colorBlindSafe: safe)261        let stats = model.snapshot?.gpu.first262        let enabled = model.settings.telemetry.bestEffortMetrics263        Page {264            PageHeader(title: "GPU", subtitle: model.gpuDevices.map(\.name).joined(separator: ", "), family: .gpu)265            CardRow {266                Card("Utilization", family: .gpu, quality: .bestEffort) {267                    if enabled, stats?.deviceUtilization != nil {268                        Readout(value: model.latest(.gpuUtilization).map { f.percent($0) } ?? "—", caption: "Device utilization reported by the graphics driver", size: 34)269                        Spacer(minLength: 0)270                        KeyValueRow(L("Renderer"), stats?.rendererUtilization.map { f.percent($0) } ?? "—", quality: .bestEffort)271                        KeyValueRow(L("Tiler"), stats?.tilerUtilization.map { f.percent($0) } ?? "—", quality: .bestEffort)272                        KeyValueRow(L("GPU cores"), stats?.coreCount.map(String.init) ?? "—", quality: .bestEffort)273                    } else if !enabled {274                        UnavailableRow(label: L("GPU utilization"), reason: L("Best-effort readings are turned off in Settings."))275                    } else {276                        UnavailableRow(label: L("GPU utilization"), reason: L("The graphics driver on this Mac publishes no utilization figure."))277                    }278                }279                .frame(minWidth: 240, maxWidth: 320)280                Card("Utilization history", family: .gpu, quality: .bestEffort) {281                    LiveChart(series: [LiveSeries(id: "gpu", name: L("GPU utilization"), color: color, points: enabled ? model.series(.gpuUtilization) : [])],282                              domain: 0...100, format: { f.percent($0) })283                }284            }285            Card("About this figure") {286                Text("macOS has no supported API for system-wide GPU utilization. The percentage above is read with a public IOKit call from a driver property whose name Apple does not document (“PerformanceStatistics” on the IOAccelerator service). It is shown as published, never adjusted, and can disappear with a system update. Turn it off in Settings › Sampling.")287                    .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)288            }289            CardRow {290                Card("Memory", family: .gpu, quality: .bestEffort) {291                    KeyValueRow(L("In use by the GPU"), stats?.memoryInUse.map { f.bytes($0, memory: true) } ?? "—", quality: .bestEffort)292                    KeyValueRow(L("Allocated by the driver"), stats?.memoryAllocated.map { f.bytes($0, memory: true) } ?? "—", quality: .bestEffort)293                    if model.gpuDevices.first?.hasUnifiedMemory == true {294                        Text("This GPU shares the Mac's unified memory; there is no separate video memory to report.")295                            .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)296                    }297                }298                Card("Not available", family: .gpu) {299                    UnavailableRow(label: L("Per-process GPU usage"))300                    UnavailableRow(label: L("GPU temperature"))301                    UnavailableRow(label: L("GPU power draw"))302                }303            }304            ForEach(model.gpuDevices) { device in305                Card(LocalizedStringKey(device.name), family: .gpu) {306                    let columns = [GridItem(.adaptive(minimum: 300), spacing: ORIX.Space.lg)]307                    LazyVGrid(columns: columns, alignment: .leading, spacing: 6) {308                        KeyValueRow(L("Unified memory"), device.hasUnifiedMemory ? L("Yes") : L("No"))309                        KeyValueRow(L("Recommended working set (Metal)"), f.bytes(device.recommendedMaxWorkingSet, memory: true))310                        KeyValueRow(L("Largest buffer (Metal)"), f.bytes(device.maxBufferLength, memory: true))311                        KeyValueRow(L("Ray tracing"), device.supportsRaytracing ? L("Supported") : L("Not supported"))312                        KeyValueRow(L("Low-power device"), device.isLowPower ? L("Yes") : L("No"))313                        KeyValueRow(L("Removable (eGPU)"), device.isRemovable ? L("Yes") : L("No"))314                        KeyValueRow(L("Headless"), device.isHeadless ? L("Yes") : L("No"))315                        KeyValueRow(L("Threads per threadgroup"), String(device.maxThreadsPerThreadgroup))316                    }317                }318            }319            SourcesCard(metrics: [.gpuUtilization])320        }321    }322}323324// MARK: - Memory325326struct MemoryView: View {327    @Environment(MonitorModel.self) private var model328    @Environment(\.colorBlindSafe) private var safe329330    var body: some View {331        let f = model.format332        let m = model.snapshot?.memory333        let c = MemoryBar.colors(safe)334        Page {335            PageHeader(title: "Memory", subtitle: String(format: L("%@ installed"), f.bytes(model.system.physicalMemory, memory: true)), family: .memory)336            CardRow {337                Card("Physical memory", family: .memory) {338                    HStack(alignment: .firstTextBaseline) {339                        Readout(value: m.map { f.bytes($0.used, memory: true) } ?? "—", caption: "used (app + wired + compressed)", size: 34)340                        Spacer()341                        if let m { PressureBadge(level: m.pressure) }342                    }343                    if let m { MemoryBar(memory: m) }344                    KeyValueRow(L("App memory"), m.map { f.bytes($0.app, memory: true) } ?? "—", swatch: c.app)345                    KeyValueRow(L("Wired memory"), m.map { f.bytes($0.wired, memory: true) } ?? "—", swatch: c.wired)346                    KeyValueRow(L("Compressed"), m.map { f.bytes($0.compressed, memory: true) } ?? "—", swatch: c.compressed)347                    KeyValueRow(L("Cached files"), m.map { f.bytes($0.cached, memory: true) } ?? "—", swatch: c.cached)348                    KeyValueRow(L("Free"), m.map { f.bytes($0.free, memory: true) } ?? "—", swatch: ORIX.Palette.surfaceRaised)349                }350                .frame(minWidth: 280, maxWidth: 380)351                Card("Memory in use", family: .memory) {352                    LiveChart(series: [353                        LiveSeries(id: "app", name: L("App memory"), color: c.app, points: model.series(.memApp)),354                        LiveSeries(id: "wired", name: L("Wired memory"), color: c.wired, points: model.series(.memWired)),355                        LiveSeries(id: "compressed", name: L("Compressed"), color: c.compressed, points: model.series(.memCompressed)),356                    ], domain: 0...Double(model.system.physicalMemory), format: { f.bytes($0, memory: true) }, stacked: true, height: 210)357                }358            }359            CardRow {360                Card("Pressure", family: .memory) {361                    LiveChart(series: [LiveSeries(id: "pressure", name: L("Memory pressure level"), color: ORIX.Palette.warning, points: model.series(.memPressure))],362                              domain: 0...2, format: { $0 >= 1.5 ? L("Critical") : $0 >= 0.5 ? L("Warning") : L("Normal") }, height: 120, ticks: [0, 1, 2])363                    Text("Pressure is the kernel's own three-level signal. It, not the amount of free memory, tells whether the Mac is short of memory.")364                        .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)365                }366                Card("Swap and paging", family: .memory) {367                    KeyValueRow(L("Swap used"), m.map { f.bytes($0.swapUsed, memory: true) } ?? "—")368                    KeyValueRow(L("Swap allocated"), m.map { f.bytes($0.swapTotal, memory: true) } ?? "—")369                    if let m, m.swapTotal > 0 { Meter(fraction: Double(m.swapUsed) / Double(m.swapTotal), color: MetricFamily.memory.color(colorBlindSafe: safe)) }370                    KeyValueRow(L("Page-ins"), m?.pageInRate.map { "\(f.number($0, digits: 0))/s" } ?? "—")371                    KeyValueRow(L("Page-outs"), m?.pageOutRate.map { "\(f.number($0, digits: 0))/s" } ?? "—")372                    KeyValueRow(L("Swap-ins"), m?.swapInRate.map { "\(f.number($0, digits: 0))/s" } ?? "—")373                    KeyValueRow(L("Swap-outs"), m?.swapOutRate.map { "\(f.number($0, digits: 0))/s" } ?? "—")374                    KeyValueRow(L("Page size"), m.map { f.bytes($0.pageSize, memory: true) } ?? "—")375                }376            }377            CardRow {378                Card("How to read these numbers") {379                    VStack(alignment: .leading, spacing: 6) {380                        definition(L("Physical memory"), L("The RAM installed in the Mac. Used + cached files + free always equals it."))381                        definition(L("App memory"), L("Memory processes allocated themselves, not counting memory they marked as purgeable."))382                        definition(L("Compressed"), L("Physical RAM occupied by the compressor. The data it holds was larger before compression."))383                        definition(L("Swap"), L("Disk space holding memory pages moved out of RAM. It is not part of physical memory."))384                        definition(L("Virtual memory"), L("Address space reserved by processes. It is not a measure of RAM in use and is not shown."))385                    }386                }387                Card("Top processes by memory", family: .memory) { ProcessContribution(byMemory: true) }388            }389            SourcesCard(metrics: [.memUsed, .memApp, .memWired, .memCompressed, .memCached, .memFree, .memPressure, .swapUsed, .pageIns, .pageOuts])390        }391    }392393    private func definition(_ term: String, _ text: String) -> some View {394        VStack(alignment: .leading, spacing: 1) {395            Text(term).font(.system(size: 12, weight: .semibold))396            Text(text).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)397        }398        .accessibilityElement(children: .combine)399    }400}401
Files main
Menu

Theme