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/MenuBar.swift10// Description : Menu bar extra: a compact, configurable status image and11// the quick-diagnostics panel behind it.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 AppKit91import ORIXMonitorCore92import SwiftUI9394enum MenuBarText {95 static func title(_ item: MenuBarItem) -> String {96 switch item {97 case .cpu: L("CPU")98 case .memory: L("Memory")99 case .network: L("Network")100 case .disk: L("Disk activity")101 case .battery: L("Battery")102 }103 }104105 /// Short rate for the 22-point menu bar: “1.2M”, “340K”, “0K”.106 static func shortRate(_ bytesPerSecond: Double) -> String {107 let v = max(0, bytesPerSecond)108 if v >= 1_000_000_000 { return String(format: "%.1fG", v / 1_000_000_000) }109 if v >= 10_000_000 { return String(format: "%.0fM", v / 1_000_000) }110 if v >= 1_000_000 { return String(format: "%.1fM", v / 1_000_000) }111 return String(format: "%.0fK", v / 1000)112 }113}114115/// Draws the status item as one template image, so macOS tints it for light, dark and highlighted menu bars.116enum MenuBarRenderer {117 struct Segment {118 var caption: String119 var lines: [String]120 var graph: [Double]?121 var ceiling: Double?122 }123124 static func image(segments: [Segment], alert: Bool) -> NSImage {125 let height: CGFloat = 22126 let captionFont = NSFont.systemFont(ofSize: 7.5, weight: .bold)127 let valueFont = NSFont.monospacedDigitSystemFont(ofSize: 11.5, weight: .medium)128 let smallFont = NSFont.monospacedDigitSystemFont(ofSize: 8.5, weight: .medium)129 let graphWidth: CGFloat = 26130 func width(_ text: String, _ font: NSFont) -> CGFloat { ceil((text as NSString).size(withAttributes: [.font: font]).width) }131132 var layout: [(segment: Segment, width: CGFloat)] = []133 for s in segments {134 let font = s.lines.count > 1 ? smallFont : valueFont135 let text = max(s.lines.map { width($0, font) }.max() ?? 0, width(s.caption, captionFont))136 layout.append((s, text + (s.graph != nil ? graphWidth + 3 : 0)))137 }138 let pulseWidth: CGFloat = 18139 let total = pulseWidth + layout.reduce(0) { $0 + $1.width + 7 } + (alert ? 7 : 0)140 let image = NSImage(size: NSSize(width: max(total, pulseWidth), height: height), flipped: false) { _ in141 NSColor.black.set()142 // ORIX pulse mark: a ring cut by a heartbeat trace.143 let ring = NSBezierPath(ovalIn: NSRect(x: 2.5, y: 4.5, width: 13, height: 13))144 ring.lineWidth = 1.6145 ring.stroke()146 NSGraphicsContext.current?.cgContext.setBlendMode(.clear)147 NSBezierPath(rect: NSRect(x: 0, y: 9.4, width: 18, height: 3.2)).fill()148 NSGraphicsContext.current?.cgContext.setBlendMode(.normal)149 let pulse = NSBezierPath()150 pulse.move(to: NSPoint(x: 0.5, y: 11))151 for point in [(4.5, 11.0), (6.5, 15.5), (9.5, 6.0), (11.5, 13.0), (13.0, 11.0), (17.5, 11.0)] { pulse.line(to: NSPoint(x: point.0, y: point.1)) }152 pulse.lineWidth = 1.5153 pulse.lineJoinStyle = .round154 pulse.lineCapStyle = .round155 pulse.stroke()156157 var x = pulseWidth + 5158 for (segment, segmentWidth) in layout {159 var textX = x160 if let graph = segment.graph {161 let rect = NSRect(x: x, y: 3.5, width: graphWidth, height: 15)162 NSColor.black.withAlphaComponent(0.18).setFill()163 NSBezierPath(roundedRect: rect, xRadius: 2, yRadius: 2).fill()164 let top = max(segment.ceiling ?? (graph.max() ?? 1), .leastNonzeroMagnitude)165 let values = Array(graph.suffix(13))166 let bar = rect.width / 13167 NSColor.black.setFill()168 for (i, value) in values.enumerated() {169 let h = max(1, CGFloat(min(max(value / top, 0), 1)) * rect.height)170 NSBezierPath(rect: NSRect(x: rect.minX + CGFloat(13 - values.count + i) * bar + 0.25, y: rect.minY, width: bar - 0.5, height: h)).fill()171 }172 textX += graphWidth + 3173 }174 if segment.lines.count > 1 {175 for (i, line) in segment.lines.prefix(2).enumerated() {176 (line as NSString).draw(at: NSPoint(x: textX, y: i == 0 ? 11 : 1.5), withAttributes: [.font: smallFont, .foregroundColor: NSColor.black])177 }178 } else {179 (segment.caption as NSString).draw(at: NSPoint(x: textX, y: 12.5), withAttributes: [.font: captionFont, .foregroundColor: NSColor.black.withAlphaComponent(0.7)])180 ((segment.lines.first ?? "") as NSString).draw(at: NSPoint(x: textX, y: 0.5), withAttributes: [.font: valueFont, .foregroundColor: NSColor.black])181 }182 x += segmentWidth + 7183 }184 if alert {185 NSColor.black.setFill()186 NSBezierPath(ovalIn: NSRect(x: x - 2, y: 8, width: 6, height: 6)).fill()187 }188 return true189 }190 image.isTemplate = true191 return image192 }193}194195struct MenuBarLabel: View {196 var model: MonitorModel197 var settings: AppSettings198199 var body: some View {200 Image(nsImage: MenuBarRenderer.image(segments: segments, alert: !model.firing.isEmpty))201 .accessibilityLabel(Text(accessibilityText))202 }203204 private var segments: [MenuBarRenderer.Segment] {205 let f = model.format206 let graphs = settings.menuBarGraphs207 return settings.menuBarItems.compactMap { item in208 switch item {209 case .cpu:210 return .init(caption: "CPU", lines: [model.latest(.cpuTotal).map { f.percent($0) } ?? "–"], graph: graphs ? model.values(.cpuTotal, last: 13) : nil, ceiling: 100)211 case .memory:212 return .init(caption: "MEM", lines: [model.snapshot?.memory.map { f.percent($0.usedFraction * 100) } ?? "–"], graph: nil, ceiling: nil)213 case .network:214 return .init(caption: "", lines: ["↑ " + (model.latest(.netUp).map(MenuBarText.shortRate) ?? "–"), "↓ " + (model.latest(.netDown).map(MenuBarText.shortRate) ?? "–")],215 graph: graphs ? model.values(.netDown, last: 13) : nil, ceiling: nil)216 case .disk:217 return .init(caption: "", lines: ["R " + (model.latest(.diskRead).map(MenuBarText.shortRate) ?? "–"), "W " + (model.latest(.diskWrite).map(MenuBarText.shortRate) ?? "–")], graph: nil, ceiling: nil)218 case .battery:219 guard let p = model.snapshot?.power, p.hasBattery, let charge = p.charge else { return nil }220 return .init(caption: p.isCharging ? "CHG" : "BAT", lines: [f.percent(charge)], graph: nil, ceiling: nil)221 }222 }223 }224225 private var accessibilityText: String {226 var parts = ["ORIX Monitor"]227 if let cpu = model.latest(.cpuTotal) { parts.append("\(L("CPU")) \(model.format.percent(cpu))") }228 if let m = model.snapshot?.memory { parts.append("\(L("Memory")) \(model.format.percent(m.usedFraction * 100))") }229 if !model.firing.isEmpty { parts.append(String(format: L("%d active alerts"), model.firing.count)) }230 return parts.joined(separator: ", ")231 }232}233234struct MenuBarPanel: View {235 @Environment(MonitorModel.self) private var model236 @Environment(AppSettings.self) private var settings237 @Environment(\.openWindow) private var openWindow238 @Environment(\.openSettings) private var openSettings239 @Environment(\.colorBlindSafe) private var safe240241 var body: some View {242 let f = model.format243 VStack(alignment: .leading, spacing: ORIX.Space.sm) {244 HStack {245 Text("ORIX Monitor").font(.system(size: 13, weight: .bold))246 Spacer()247 if let s = model.snapshot { Text(ThermalText.name(s.thermal)).font(ORIX.Typeface.caption).foregroundStyle(ThermalText.color(s.thermal)).help("Thermal state") }248 Button { model.isPaused.toggle() } label: { Image(systemName: model.isPaused ? "play.fill" : "pause.fill") }249 .buttonStyle(.borderless).help(model.isPaused ? "Resume sampling" : "Pause sampling")250 .accessibilityLabel(Text(model.isPaused ? "Resume Sampling" : "Pause Sampling"))251 }252 if !model.firing.isEmpty {253 VStack(alignment: .leading, spacing: 4) {254 ForEach(model.firing) { rule in255 Label(AlertText.title(rule), systemImage: rule.severity.symbol).font(.system(size: 12, weight: .medium)).foregroundStyle(rule.severity.color)256 }257 }258 .padding(8).frame(maxWidth: .infinity, alignment: .leading)259 .background(ORIX.Palette.danger.opacity(0.10), in: RoundedRectangle(cornerRadius: 8))260 }261 tile(.cpu, L("CPU"), model.latest(.cpuTotal).map { f.percent($0) }, model.values(.cpuTotal, last: 60), 100)262 tile(.memory, L("Memory"), model.snapshot?.memory.map { "\(f.bytes($0.used, memory: true)) · \(f.percent($0.usedFraction * 100))" }, model.values(.memUsed, last: 60), Double(model.system.physicalMemory))263 tile(.network, L("Network"), model.latest(.netDown).map { d in "↓ \(f.rate(d)) ↑ \(f.rate(model.latest(.netUp) ?? 0))" }, model.values(.netDown, last: 60), nil)264 tile(.disk, L("Disk"), model.latest(.diskRead).map { r in "R \(MenuBarText.shortRate(r)) W \(MenuBarText.shortRate(model.latest(.diskWrite) ?? 0))" }, model.values(.diskWrite, last: 60), nil)265 if let p = model.snapshot?.power, p.hasBattery {266 HStack {267 Label(PowerText.state(p), systemImage: p.isCharging ? "battery.100.bolt" : "battery.75").font(.system(size: 12))268 Spacer()269 Text(p.charge.map { f.percent($0) } ?? "—").font(ORIX.Typeface.value)270 }271 .accessibilityElement(children: .combine)272 }273 Divider()274 Text("Top processes").font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary)275 let top = (model.processes?.processes ?? []).filter { $0.cpuPercent != nil }.sorted { ($0.cpuPercent ?? 0) > ($1.cpuPercent ?? 0) }.prefix(4)276 ForEach(Array(top)) { p in277 HStack {278 Text(p.name).font(.system(size: 12)).lineLimit(1).truncationMode(.middle)279 Spacer()280 Text(f.percent(p.cpuPercent ?? 0, digits: 1)).font(ORIX.Typeface.value)281 }282 .accessibilityElement(children: .combine)283 }284 Divider()285 HStack {286 Button("Open ORIX Monitor") {287 openWindow(id: "main")288 NSApp.activate(ignoringOtherApps: true)289 }290 .keyboardShortcut("o")291 .accessibilityIdentifier("menubar.open")292 Spacer()293 Button {294 openSettings()295 NSApp.activate(ignoringOtherApps: true)296 } label: { Image(systemName: "gearshape") }.buttonStyle(.borderless).accessibilityLabel(Text("Settings"))297 Button { NSApp.terminate(nil) } label: { Image(systemName: "power") }.buttonStyle(.borderless).help("Quit ORIX Monitor").accessibilityLabel(Text("Quit ORIX Monitor"))298 }299 }300 .padding(ORIX.Space.md)301 .frame(width: 310)302 }303304 private func tile(_ family: MetricFamily, _ title: String, _ value: String?, _ spark: [Double], _ ceiling: Double?) -> some View {305 HStack(spacing: ORIX.Space.sm) {306 Image(systemName: family.symbol).frame(width: 18).foregroundStyle(family.color(colorBlindSafe: safe)).accessibilityHidden(true)307 VStack(alignment: .leading, spacing: 0) {308 Text(title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary)309 Text(value ?? "—").font(ORIX.Typeface.value)310 }311 Spacer()312 Sparkline(values: spark, color: family.color(colorBlindSafe: safe), ceiling: ceiling).frame(width: 90, height: 24)313 }314 .accessibilityElement(children: .combine)315 }316}317