SPB Git

Repository Public License

DashboardView.swift 28.5 KB 630 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Monitor9// File             : App/Sources/Features/DashboardView.swift10// Description      : Customisable overview: a flow grid of live widgets with11//                    drag-and-drop reordering, resizing and saved presets.12// Module           : Features13// Repository       : https://git.spboucher.ai/orix-monitor14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : Proprietary, all rights reserved (see license file)82// License File     : LICENSE83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import ORIXMonitorCore91import SwiftUI9293/// Packs widgets into rows of equal-width columns. Each widget spans 1, 2 or all columns.94struct FlowGrid: Layout {95    var minColumnWidth: CGFloat = 25096    var rowHeight: CGFloat = 17697    var spacing: CGFloat = 169899    struct SpanKey: LayoutValueKey { static let defaultValue = 1 }100101    private func columns(for width: CGFloat) -> Int {102        max(1, min(4, Int((width + spacing) / (minColumnWidth + spacing))))103    }104105    private func place(_ subviews: Subviews, width: CGFloat) -> (frames: [CGRect], height: CGFloat) {106        let count = columns(for: width)107        let column = (width - CGFloat(count - 1) * spacing) / CGFloat(count)108        var frames: [CGRect] = []109        var x = 0, y: CGFloat = 0110        for subview in subviews {111            let span = min(subview[SpanKey.self], count)112            if x + span > count {113                x = 0114                y += rowHeight + spacing115            }116            frames.append(CGRect(x: CGFloat(x) * (column + spacing), y: y, width: CGFloat(span) * column + CGFloat(span - 1) * spacing, height: rowHeight))117            x += span118        }119        return (frames, subviews.isEmpty ? 0 : y + rowHeight)120    }121122    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {123        let width = proposal.width ?? 900124        return CGSize(width: width, height: place(subviews, width: width).height)125    }126127    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {128        let frames = place(subviews, width: bounds.width).frames129        for (subview, frame) in zip(subviews, frames) {130            subview.place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY), proposal: ProposedViewSize(frame.size))131        }132    }133}134135struct DashboardView: View {136    @Environment(MonitorModel.self) private var model137    @Environment(AppSettings.self) private var settings138    @Environment(\.density) private var density139    @Environment(\.openWindow) private var openWindow140    @Environment(\.accessibilityReduceMotion) private var reduceMotion141    @State var presetID: UUID142    var isDetached: Bool143    @State private var isEditing = false144    @State private var newPresetName = ""145    @State private var askName = false146    @State private var dropTarget: UUID?147148    private var preset: DashboardPreset { settings.preset(presetID) }149150    var body: some View {151        ScrollView {152            VStack(alignment: .leading, spacing: ORIX.Space.md * density) {153                header154                FlowGrid(rowHeight: 176 * max(density, 0.85), spacing: ORIX.Space.md * density) {155                    ForEach(preset.widgets) { widget in156                        WidgetView(widget: widget)157                            .overlay(alignment: .topTrailing) { if isEditing { editControls(widget) } }158                            .overlay {159                                if dropTarget == widget.id {160                                    RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous).strokeBorder(ORIX.Palette.accent, lineWidth: 2)161                                }162                            }163                            .layoutValue(key: FlowGrid.SpanKey.self, value: widget.size.rawValue)164                            .draggable(widget.id.uuidString) {165                                Label(WidgetCatalog.title(widget.kind), systemImage: widget.kind.family.symbol).padding(8)166                                    .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: 8))167                            }168                            .dropDestination(for: String.self) { items, _ in169                                guard let source = items.first.flatMap(UUID.init) else { return false }170                                move(source, before: widget.id)171                                return true172                            } isTargeted: { dropTarget = $0 ? widget.id : (dropTarget == widget.id ? nil : dropTarget) }173                            .accessibilityIdentifier("widget.\(widget.kind.rawValue)")174                    }175                }176                if preset.widgets.isEmpty {177                    ContentUnavailableView("No widgets", systemImage: "square.grid.2x2", description: Text("Use Add Widget to build this dashboard."))178                        .frame(maxWidth: .infinity, minHeight: 240)179                }180            }181            .padding(ORIX.Space.lg * density)182        }183        .background(ORIX.Palette.canvas)184        .onChange(of: settings.selectedPreset) { _, new in if !isDetached { presetID = new } }185        .alert("Save Layout As", isPresented: $askName) {186            TextField("Name", text: $newPresetName)187            Button("Save") {188                let name = newPresetName.trimmingCharacters(in: .whitespaces)189                guard !name.isEmpty else { return }190                select(settings.duplicatePreset(presetID, name: name))191            }192            Button("Cancel", role: .cancel) {}193        }194    }195196    private func select(_ id: UUID) {197        presetID = id198        if !isDetached { settings.selectedPreset = id }199    }200201    private var header: some View {202        HStack(spacing: ORIX.Space.sm) {203            VStack(alignment: .leading, spacing: 1) {204                Text(preset.isBuiltIn ? L(preset.name) : preset.name).font(.system(size: 20, weight: .bold))205                Text("\(model.system.chip) · macOS \(model.system.osVersion) · \(model.format.bytes(model.system.physicalMemory, memory: true))")206                    .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)207            }208            Spacer()209            Menu {210                ForEach(settings.presets) { item in211                    Button { select(item.id) } label: {212                        if item.id == presetID { Label(item.isBuiltIn ? L(item.name) : item.name, systemImage: "checkmark") } else { Text(item.isBuiltIn ? L(item.name) : item.name) }213                    }214                }215                Divider()216                Button("Save Layout As…") {217                    newPresetName = ""218                    askName = true219                }220                if preset.isBuiltIn {221                    Button("Reset to Default") { settings.resetBuiltIn(presetID) }222                } else {223                    Button("Delete Layout", role: .destructive) {224                        let id = presetID225                        select(DashboardPreset.overviewID)226                        settings.deletePreset(id)227                    }228                }229                if !isDetached {230                    Divider()231                    Button("Open in New Window") { openWindow(id: "dashboard", value: presetID) }232                }233            } label: { Label("Layout", systemImage: "rectangle.3.group") }234                .menuStyle(.borderlessButton).fixedSize()235                .accessibilityIdentifier("dashboard.layout")236            if isEditing {237                Menu {238                    ForEach(WidgetKind.allCases) { kind in239                        Button { add(kind) } label: { Label(WidgetCatalog.title(kind), systemImage: kind.family.symbol) }240                    }241                } label: { Label("Add Widget", systemImage: "plus") }242                    .menuStyle(.borderlessButton).fixedSize()243                    .accessibilityIdentifier("dashboard.add")244            }245            Toggle(isOn: $isEditing.animation(reduceMotion ? nil : .snappy(duration: 0.2))) { Label("Edit", systemImage: "slider.horizontal.3") }246                .toggleStyle(.button)247                .accessibilityIdentifier("dashboard.edit")248        }249    }250251    private func editControls(_ widget: WidgetConfig) -> some View {252        HStack(spacing: 4) {253            Menu {254                Picker("Size", selection: Binding(get: { widget.size }, set: { resize(widget.id, $0) })) {255                    Text("Small").tag(WidgetSize.small)256                    Text("Wide").tag(WidgetSize.medium)257                    Text("Full width").tag(WidgetSize.large)258                }259                .pickerStyle(.inline)260                Button("Move Earlier") { shift(widget.id, by: -1) }261                Button("Move Later") { shift(widget.id, by: 1) }262            } label: { Image(systemName: "arrow.up.left.and.arrow.down.right") }263                .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()264                .accessibilityLabel(Text("Resize or move \(WidgetCatalog.title(widget.kind))"))265            Button { remove(widget.id) } label: { Image(systemName: "xmark.circle.fill") }266                .buttonStyle(.plain)267                .accessibilityLabel(Text("Remove \(WidgetCatalog.title(widget.kind))"))268        }269        .font(.system(size: 13))270        .foregroundStyle(ORIX.Palette.textSecondary)271        .padding(6)272        .background(.ultraThinMaterial, in: Capsule())273        .padding(6)274    }275276    private func mutate(_ change: (inout [WidgetConfig]) -> Void) {277        var widgets = preset.widgets278        change(&widgets)279        withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { settings.updateWidgets(widgets, in: presetID) }280    }281282    private func add(_ kind: WidgetKind) { mutate { $0.append(WidgetConfig(kind: kind, size: WidgetCatalog.defaultSize(kind))) } }283    private func remove(_ id: UUID) { mutate { $0.removeAll { $0.id == id } } }284    private func resize(_ id: UUID, _ size: WidgetSize) { mutate { if let i = $0.firstIndex(where: { $0.id == id }) { $0[i].size = size } } }285    private func shift(_ id: UUID, by offset: Int) {286        mutate {287            guard let i = $0.firstIndex(where: { $0.id == id }) else { return }288            let j = min(max(i + offset, 0), $0.count - 1)289            $0.swapAt(i, j)290        }291    }292293    private func move(_ source: UUID, before target: UUID) {294        guard source != target else { return }295        mutate {296            guard let from = $0.firstIndex(where: { $0.id == source }) else { return }297            let item = $0.remove(at: from)298            let to = $0.firstIndex(where: { $0.id == target }) ?? $0.count299            $0.insert(item, at: to)300        }301        dropTarget = nil302    }303}304305enum WidgetCatalog {306    static func title(_ kind: WidgetKind) -> String {307        switch kind {308        case .cpu: L("CPU")309        case .cores: L("CPU cores")310        case .gpu: L("GPU")311        case .memory: L("Memory")312        case .disk: L("Storage")313        case .diskActivity: L("Disk activity")314        case .network: L("Network")315        case .battery: L("Battery")316        case .thermal: L("Thermal state")317        case .topCPU: L("Top processes by CPU")318        case .topMemory: L("Top processes by memory")319        case .system: L("System")320        case .alerts: L("Alerts")321        case .overhead: L("ORIX Monitor overhead")322        }323    }324325    static func defaultSize(_ kind: WidgetKind) -> WidgetSize {326        switch kind {327        case .topCPU, .topMemory, .cores, .disk, .alerts, .overhead: .medium328        default: .small329        }330    }331}332333struct WidgetView: View {334    var widget: WidgetConfig335    @Environment(MonitorModel.self) private var model336    @Environment(\.colorBlindSafe) private var safe337338    private var color: Color { widget.kind.family.color(colorBlindSafe: safe) }339    private var f: ValueFormatter { model.format }340    private var wide: Bool { widget.size != .small }341342    var body: some View {343        Card(LocalizedStringKey(WidgetCatalog.title(widget.kind)), family: widget.kind.family, quality: quality) { content }344    }345346    private var quality: MetricQuality? {347        switch widget.kind {348        case .gpu: .bestEffort349        default: nil350        }351    }352353    @ViewBuilder private var content: some View {354        switch widget.kind {355        case .cpu:356            metric(value: model.latest(.cpuTotal).map { f.percent($0) }, caption: cpuCaption, spark: model.values(.cpuTotal, last: wide ? 120 : 60), ceiling: 100)357        case .gpu:358            if model.settings.telemetry.bestEffortMetrics {359                metric(value: model.latest(.gpuUtilization).map { f.percent($0) }, caption: model.gpuDevices.first?.name ?? "", spark: model.values(.gpuUtilization, last: wide ? 120 : 60), ceiling: 100)360            } else {361                UnavailableRow(label: L("GPU utilization"), reason: L("Best-effort readings are turned off in Settings."))362            }363        case .memory:364            if let m = model.snapshot?.memory {365                VStack(alignment: .leading, spacing: ORIX.Space.xs) {366                    HStack(alignment: .firstTextBaseline) {367                        Readout(value: f.bytes(m.used, memory: true), caption: "of \(f.bytes(m.physical, memory: true)) used")368                        Spacer()369                        PressureBadge(level: m.pressure)370                    }371                    Spacer(minLength: 0)372                    MemoryBar(memory: m)373                    if wide { KeyValueRow(L("Swap used"), f.bytes(m.swapUsed, memory: true)) }374                }375            } else { waiting }376        case .disk:377            VStack(alignment: .leading, spacing: ORIX.Space.xs) {378                ForEach(model.snapshot?.volumes.prefix(3) ?? []) { volume in379                    VStack(alignment: .leading, spacing: 3) {380                        HStack {381                            Text(volume.name).font(.system(size: 12, weight: .medium)).lineLimit(1)382                            Spacer()383                            Text("\(f.bytes(volume.available)) available").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)384                        }385                        Meter(fraction: volume.usedFraction, color: volume.usedFraction > 0.9 ? ORIX.Palette.danger : color)386                    }387                    .accessibilityElement(children: .combine)388                }389                if model.snapshot == nil { waiting }390            }391        case .diskActivity:392            dual(top: (L("Read"), model.latest(.diskRead)), bottom: (L("Write"), model.latest(.diskWrite)), a: .diskRead, b: .diskWrite)393        case .network:394            dual(top: (L("Download"), model.latest(.netDown)), bottom: (L("Upload"), model.latest(.netUp)), a: .netDown, b: .netUp)395        case .battery:396            if let p = model.snapshot?.power, p.hasBattery {397                VStack(alignment: .leading, spacing: ORIX.Space.xs) {398                    Readout(value: p.charge.map { f.percent($0) } ?? "—", caption: LocalizedStringKey(PowerText.state(p)))399                    Spacer(minLength: 0)400                    Meter(fraction: (p.charge ?? 0) / 100, color: (p.charge ?? 100) < 15 ? ORIX.Palette.danger : color)401                    if let minutes = p.minutesToEmpty ?? p.minutesToFull {402                        KeyValueRow(p.minutesToFull != nil ? L("Until full") : L("Remaining"), f.duration(Double(minutes) * 60), quality: .estimated)403                    }404                }405            } else if model.snapshot != nil {406                VStack(alignment: .leading, spacing: 4) {407                    Readout(value: L("AC power"), size: 20)408                    Text("This Mac has no battery.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)409                }410            } else { waiting }411        case .thermal:412            if let s = model.snapshot {413                VStack(alignment: .leading, spacing: ORIX.Space.xs) {414                    Readout(value: ThermalText.name(s.thermal), caption: "Reported by macOS", size: 22, color: ThermalText.color(s.thermal))415                    Spacer(minLength: 0)416                    ThermalScale(level: s.thermal)417                }418            } else { waiting }419        case .topCPU: topProcesses(byMemory: false)420        case .topMemory: topProcesses(byMemory: true)421        case .system:422            VStack(alignment: .leading, spacing: 5) {423                KeyValueRow(L("Uptime"), f.duration(model.system.uptime))424                KeyValueRow(L("Processes"), model.processes.map { String($0.total) } ?? "—")425                KeyValueRow(L("Load average (1 min)"), model.snapshot?.cpu?.loadAverage.first.map { f.number($0, digits: 2) } ?? "—")426                KeyValueRow(L("Model"), model.system.model)427            }428        case .alerts:429            if model.firing.isEmpty {430                VStack(alignment: .leading, spacing: 4) {431                    Label("No active alert", systemImage: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.success).font(.system(size: 13, weight: .medium))432                    Text("\(model.settings.rules.filter(\.isEnabled).count) rules are being watched.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)433                    if !model.findings.isEmpty {434                        Text("\(model.findings.count) findings in the last 24 hours.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)435                    }436                }437            } else {438                VStack(alignment: .leading, spacing: 5) {439                    ForEach(model.firing.prefix(4)) { rule in440                        Label(AlertText.title(rule), systemImage: rule.severity.symbol).foregroundStyle(rule.severity.color).font(.system(size: 12, weight: .medium)).lineLimit(1)441                    }442                }443            }444        case .cores:445            if let cores = model.snapshot?.cpu?.cores {446                CoreBars(cores: cores, color: color)447            } else { waiting }448        case .overhead:449            VStack(alignment: .leading, spacing: 5) {450                KeyValueRow(L("CPU (of one core)"), model.latest(.selfCPU).map { f.percent($0, digits: 1) } ?? "—")451                KeyValueRow(L("Memory footprint"), model.snapshot.map { f.bytes($0.selfMemory, memory: true) } ?? "—")452                KeyValueRow(L("Collection time per sample"), model.snapshot.map { "\(f.number($0.collectionTime, digits: 1)) ms" } ?? "—")453                Sparkline(values: model.values(.selfCPU, last: 120), color: color).frame(maxHeight: .infinity)454            }455        }456    }457458    private var cpuCaption: String {459        guard let cpu = model.snapshot?.cpu else { return "" }460        return String(format: L("User %1$@ · System %2$@"), f.percent(cpu.total.user * 100), f.percent(cpu.total.system * 100))461    }462463    private var waiting: some View {464        Text("Collecting samples…").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).frame(maxWidth: .infinity, maxHeight: .infinity)465    }466467    private func metric(value: String?, caption: String, spark: [Double], ceiling: Double?) -> some View {468        VStack(alignment: .leading, spacing: ORIX.Space.xs) {469            Readout(value: value ?? "—", caption: LocalizedStringKey(caption))470            Sparkline(values: spark, color: color, ceiling: ceiling).frame(maxHeight: .infinity)471        }472    }473474    private func dual(top: (String, Double?), bottom: (String, Double?), a: MetricID, b: MetricID) -> some View {475        let ceiling = max((model.values(a, last: 120) + model.values(b, last: 120)).max() ?? 1, 1024)476        return VStack(alignment: .leading, spacing: 4) {477            HStack(alignment: .firstTextBaseline) {478                Readout(value: top.1.map { f.rate($0) } ?? "—", caption: LocalizedStringKey(top.0), size: 20)479                Spacer()480                Readout(value: bottom.1.map { f.rate($0) } ?? "—", caption: LocalizedStringKey(bottom.0), size: 20, color: ORIX.Palette.textSecondary)481            }482            ZStack {483                Sparkline(values: model.values(a, last: wide ? 120 : 60), color: color, ceiling: ceiling)484                Sparkline(values: model.values(b, last: wide ? 120 : 60), color: ORIX.Palette.textSecondary, ceiling: ceiling, filled: false)485            }486            .frame(maxHeight: .infinity)487        }488    }489490    private func topProcesses(byMemory: Bool) -> some View {491        let rows = (model.processes?.processes ?? []).filter { $0.hasStatistics && (byMemory || $0.cpuPercent != nil) }492            .sorted { byMemory ? $0.memory > $1.memory : ($0.cpuPercent ?? -1) > ($1.cpuPercent ?? -1) }.prefix(5)493        return VStack(alignment: .leading, spacing: 5) {494            ForEach(Array(rows)) { p in495                HStack {496                    Text(p.name).font(.system(size: 12)).lineLimit(1).truncationMode(.middle)497                    Spacer()498                    Text(byMemory ? f.bytes(p.memory, memory: true) : (p.cpuPercent.map { f.percent($0, digits: 1) } ?? "—")).font(ORIX.Typeface.value)499                }500                .accessibilityElement(children: .combine)501            }502            if rows.isEmpty { waiting }503            Spacer(minLength: 0)504        }505    }506}507508/// One thin vertical bar per logical core.509struct CoreBars: View {510    var cores: [CPULoad]511    var color: Color512513    var body: some View {514        GeometryReader { proxy in515            HStack(alignment: .bottom, spacing: 3) {516                ForEach(Array(cores.enumerated()), id: \.offset) { _, core in517                    ZStack(alignment: .bottom) {518                        RoundedRectangle(cornerRadius: 2).fill(ORIX.Palette.surfaceRaised)519                        RoundedRectangle(cornerRadius: 2).fill(color).frame(height: max(2, proxy.size.height * CGFloat(core.busy)))520                    }521                }522            }523        }524        .accessibilityElement(children: .ignore)525        .accessibilityLabel(Text("CPU cores"))526        .accessibilityValue(Text(cores.enumerated().map { "\($0.offset + 1): \(Int(($0.element.busy * 100).rounded())) %" }.joined(separator: ", ")))527    }528}529530struct PressureBadge: View {531    var level: MemoryPressureLevel532533    var body: some View {534        let (text, color): (String, Color) = switch level {535        case .normal: (L("Normal"), ORIX.Palette.success)536        case .warning: (L("Warning"), ORIX.Palette.warning)537        case .critical: (L("Critical"), ORIX.Palette.danger)538        }539        Label(text, systemImage: level == .normal ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")540            .font(.system(size: 11, weight: .semibold))541            .foregroundStyle(color)542            .padding(.horizontal, 7).padding(.vertical, 3)543            .background(color.opacity(0.14), in: Capsule())544            .accessibilityLabel(Text("Memory pressure: \(text)"))545    }546}547548struct MemoryBar: View {549    var memory: MemorySample550    @Environment(\.colorBlindSafe) private var safe551552    static func colors(_ safe: Bool) -> (app: Color, wired: Color, compressed: Color, cached: Color) {553        (MetricFamily.memory.color(colorBlindSafe: safe), MetricFamily.disk.color(colorBlindSafe: safe),554         MetricFamily.gpu.color(colorBlindSafe: safe), MetricFamily.network.color(colorBlindSafe: safe).opacity(0.45))555    }556557    var body: some View {558        let c = Self.colors(safe)559        SegmentBar(segments: [560            .init(id: "app", value: Double(memory.app), color: c.app), .init(id: "wired", value: Double(memory.wired), color: c.wired),561            .init(id: "compressed", value: Double(memory.compressed), color: c.compressed), .init(id: "cached", value: Double(memory.cached), color: c.cached),562        ], total: Double(memory.physical))563    }564}565566enum ThermalText {567    static func name(_ level: ThermalLevel) -> String {568        switch level {569        case .nominal: L("Nominal")570        case .fair: L("Fair")571        case .serious: L("Serious")572        case .critical: L("Critical")573        }574    }575576    static func color(_ level: ThermalLevel) -> Color {577        switch level {578        case .nominal: ORIX.Palette.success579        case .fair: ORIX.Palette.textPrimary580        case .serious: ORIX.Palette.warning581        case .critical: ORIX.Palette.danger582        }583    }584585    static func explanation(_ level: ThermalLevel) -> String {586        switch level {587        case .nominal: L("The system is within its normal thermal range.")588        case .fair: L("The system is slightly warm. Performance is not affected.")589        case .serious: L("The system is hot. macOS may reduce performance.")590        case .critical: L("The system is very hot. macOS is reducing performance to cool down.")591        }592    }593}594595/// Four steps, the current one highlighted. The label next to it carries the meaning; colour is secondary.596struct ThermalScale: View {597    var level: ThermalLevel598599    var body: some View {600        HStack(spacing: 3) {601            ForEach(0..<4, id: \.self) { step in602                Capsule().fill(step <= level.rawValue ? ThermalText.color(level) : ORIX.Palette.surfaceRaised).frame(height: 6)603            }604        }605        .accessibilityHidden(true)606    }607}608609enum PowerText {610    static func state(_ p: PowerSample) -> String {611        if p.isCharged { return L("Fully charged") }612        if p.isCharging { return L("Charging") }613        switch p.source {614        case .ac: return L("On AC power, not charging")615        case .battery: return L("On battery")616        case .ups: return L("On UPS power")617        case .unknown: return L("Power source unknown")618        }619    }620621    static func source(_ kind: PowerSourceKind) -> String {622        switch kind {623        case .ac: L("AC adapter")624        case .battery: L("Battery")625        case .ups: L("UPS")626        case .unknown: L("Unknown")627        }628    }629}630
Files main
Menu

Theme