Repository navigation
Expand file tree
/
Copy pathstatbar.swift
More file actions
420 lines (340 loc) · 15.1 KB
/
Copy pathstatbar.swift
File metadata and controls
420 lines (340 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import Cocoa
import Darwin
// MARK: - Data Models
struct CPUData {
var performanceCoreValues: [Int]
var efficiencyCoreValues: [Int]
var performanceCoreCount: Int
var coreCount: Int { max(performanceCoreValues.count + efficiencyCoreValues.count, performanceCoreCount) }
}
struct MemoryData {
var wiredCompressedPercent: Int
var appMemoryPercent: Int
var cachedFilesPercent: Int
var pressureLevel: Int
var pressureLabel: String
}
// MARK: - CPUView
class CPUView: NSView {
// MARK: Properties
var cpuData = CPUData(performanceCoreValues: [], efficiencyCoreValues: [], performanceCoreCount: 0) {
didSet { invalidateIntrinsicContentSize() }
}
var memoryData = MemoryData(wiredCompressedPercent: 0, appMemoryPercent: 0, cachedFilesPercent: 0, pressureLevel: 1, pressureLabel: "正常")
var showPopover: (() -> Void)?
var hidePopover: (() -> Void)?
// MARK: Metrics
private enum Metrics {
static let barWidth: CGFloat = 5
static let barHeight: CGFloat = 22
static let barGap: CGFloat = 2
static let memoryBarWidth: CGFloat = 12
static let memoryBarGap: CGFloat = 4
static let cornerRadius: CGFloat = 1
static let backgroundCornerRadius: CGFloat = 3
}
// MARK: Mouse Tracking
override func updateTrackingAreas() {
if let existing = trackingAreas.first { removeTrackingArea(existing) }
let area = NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeAlways], owner: self)
addTrackingArea(area)
}
override func mouseEntered(with event: NSEvent) { showPopover?() }
override func mouseExited(with event: NSEvent) { hidePopover?() }
// MARK: Layout
private func totalWidth(for cores: Int) -> CGFloat {
CGFloat(cores) * (Metrics.barWidth + Metrics.barGap) + Metrics.memoryBarGap + Metrics.memoryBarWidth
}
override var intrinsicContentSize: NSSize {
NSSize(width: totalWidth(for: cpuData.coreCount), height: Metrics.barHeight)
}
// MARK: Drawing
override func draw(_ dirtyRect: NSRect) {
let cores = cpuData.coreCount
guard cores > 0 else { return }
drawBackground(cores: cores)
drawCPUBars(cores: cores)
drawMemoryBar(cores: cores)
}
private func drawBackground(cores: Int) {
let box = NSRect(x: 0, y: 0, width: totalWidth(for: cores), height: Metrics.barHeight)
let path = NSBezierPath(roundedRect: box, xRadius: Metrics.backgroundCornerRadius, yRadius: Metrics.backgroundCornerRadius)
NSColor.black.withAlphaComponent(0.12).setFill()
path.fill()
}
private func drawCPUBars(cores: Int) {
for i in 0..<cores {
let isPerformanceCore = i < cpuData.performanceCoreCount
let percent: Int = {
if isPerformanceCore {
return i < cpuData.performanceCoreValues.count ? cpuData.performanceCoreValues[i] : 0
} else {
let ei = i - cpuData.performanceCoreCount
return ei < cpuData.efficiencyCoreValues.count ? cpuData.efficiencyCoreValues[ei] : 0
}
}()
let x = CGFloat(i) * (Metrics.barWidth + Metrics.barGap)
let barRect = NSRect(x: x, y: 0, width: Metrics.barWidth, height: Metrics.barHeight)
// Background
let bgColor = (isPerformanceCore ? NSColor.systemBlue : NSColor.systemGray).withAlphaComponent(0.35)
fillRoundedRect(barRect, color: bgColor)
// Fill
let fillHeight = Metrics.barHeight * CGFloat(percent) / 100.0
if fillHeight > 0 {
let fillRect = NSRect(x: x, y: 0, width: Metrics.barWidth, height: fillHeight)
fillRoundedRect(fillRect, color: cpuBarColor(for: percent))
}
}
}
private func drawMemoryBar(cores: Int) {
let x = totalWidth(for: cores) - Metrics.memoryBarWidth
let rect = NSRect(x: x, y: 0, width: Metrics.memoryBarWidth, height: Metrics.barHeight)
// Background
fillRoundedRect(rect, color: NSColor.white.withAlphaComponent(0.25))
// Layer 1 (bottom): Wired + Compressed
let wiredCompHeight = Metrics.barHeight * min(CGFloat(memoryData.wiredCompressedPercent), 100) / 100.0
if wiredCompHeight > 0 {
let layerRect = NSRect(x: x, y: 0, width: Metrics.memoryBarWidth, height: wiredCompHeight)
fillRoundedRect(layerRect, color: pressureColor(for: memoryData.pressureLevel))
}
// Layer 2 (middle): App memory
let appY = wiredCompHeight
let appHeight = Metrics.barHeight * min(CGFloat(memoryData.appMemoryPercent), 100) / 100.0
if appHeight > 0 {
let layerRect = NSRect(x: x, y: appY, width: Metrics.memoryBarWidth, height: appHeight)
fillRoundedRect(layerRect, color: NSColor.systemPurple.withAlphaComponent(0.50))
}
// Layer 3 (top): Cached files
let cachedY = appY + appHeight
let cachedHeight = Metrics.barHeight * min(CGFloat(memoryData.cachedFilesPercent), 100) / 100.0
if cachedHeight > 0 {
let layerRect = NSRect(x: x, y: cachedY, width: Metrics.memoryBarWidth, height: cachedHeight)
fillRoundedRect(layerRect, color: NSColor.systemBlue.withAlphaComponent(0.40))
}
}
// MARK: Color Helpers
private func fillRoundedRect(_ rect: NSRect, color: NSColor) {
color.setFill()
NSBezierPath(roundedRect: rect, xRadius: Metrics.cornerRadius, yRadius: Metrics.cornerRadius).fill()
}
private func cpuBarColor(for percent: Int) -> NSColor {
if percent > 70 {
return NSColor.systemRed.withAlphaComponent(0.75)
} else if percent > 40 {
return NSColor.systemOrange.withAlphaComponent(0.75)
} else {
return NSColor.systemGreen.withAlphaComponent(0.65)
}
}
private func pressureColor(for level: Int) -> NSColor {
switch level {
case 4: return NSColor.systemRed.withAlphaComponent(0.85)
case 2: return NSColor.systemOrange.withAlphaComponent(0.85)
default: return NSColor.systemGreen.withAlphaComponent(0.75)
}
}
}
// MARK: - DetailPopover
class DetailPopover: NSViewController {
let textLabel = NSTextField(labelWithString: "")
override func loadView() {
view = NSView(frame: NSRect(x: 0, y: 0, width: 220, height: 200))
}
override func viewDidLoad() {
super.viewDidLoad()
textLabel.font = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
textLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textLabel)
NSLayoutConstraint.activate([
textLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 12),
textLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 12),
textLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -12),
textLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -12),
])
}
func update(cpu: CPUData, memory: MemoryData) {
let pLines = cpu.performanceCoreValues.enumerated()
.map { " P\($0 + 1) → \($1)%" }
.joined(separator: "\n")
let eLines = cpu.efficiencyCoreValues.enumerated()
.map { " E\($0 + 1) → \($1)%" }
.joined(separator: "\n")
let totalUsed = memory.wiredCompressedPercent + memory.appMemoryPercent
textLabel.stringValue = """
CPU
\(pLines)
\(eLines)
内存 已使用 \(totalUsed)%
联动+压缩 → \(memory.wiredCompressedPercent)%
App 内存 → \(memory.appMemoryPercent)%
已缓存 → \(memory.cachedFilesPercent)%
压力 → \(memory.pressureLabel)
"""
}
}
// MARK: - AppDelegate
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: Properties
var statusItem: NSStatusItem!
var cpuView: CPUView!
var popover: NSPopover!
var popoverController: DetailPopover!
private var previousBusy: [UInt64] = []
private var previousIdle: [UInt64] = []
let performanceCoreCount: Int = {
var val: Int32 = 0
var size = MemoryLayout<Int32>.size
sysctlbyname("hw.perflevel0.logicalcpu_max", &val, &size, nil, 0)
return Int(val)
}()
// MARK: Lifecycle
func applicationDidFinishLaunching(_ notification: Notification) {
setupPopover()
setupMenuBar()
update()
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.update() }
}
private func setupPopover() {
popoverController = DetailPopover()
popover = NSPopover()
popover.contentViewController = popoverController
popover.behavior = .transient
}
private func setupMenuBar() {
cpuView = CPUView(frame: .zero)
cpuView.translatesAutoresizingMaskIntoConstraints = false
// Set P-core count for layout before first draw
cpuView.cpuData.performanceCoreCount = performanceCoreCount
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.addSubview(cpuView)
statusItem.button?.target = self
statusItem.button?.action = #selector(togglePopover)
statusItem.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
cpuView.showPopover = { [weak self] in self?.showPopover() }
cpuView.hidePopover = { [weak self] in self?.popover.close() }
NSLayoutConstraint.activate([
cpuView.leadingAnchor.constraint(equalTo: statusItem.button!.leadingAnchor),
cpuView.trailingAnchor.constraint(equalTo: statusItem.button!.trailingAnchor),
cpuView.centerYAnchor.constraint(equalTo: statusItem.button!.centerYAnchor),
cpuView.heightAnchor.constraint(equalToConstant: 24),
])
}
// MARK: Popover
private func showPopover() {
guard let button = statusItem.button, !popover.isShown else { return }
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .maxY)
}
@objc func togglePopover() {
if popover.isShown {
popover.close()
} else {
openActivityMonitor()
}
}
@objc func openActivityMonitor() {
NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Utilities/Activity Monitor.app"))
}
// MARK: Sampling
func sampleCPU() -> CPUData {
var size: mach_msg_type_number_t = 0
var info: processor_info_array_t? = nil
var count: mach_msg_type_number_t = 0
guard host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &count, &info, &size) == KERN_SUCCESS,
let info = info, size >= 4 else {
return CPUData(performanceCoreValues: [], efficiencyCoreValues: [], performanceCoreCount: performanceCoreCount)
}
defer { vm_deallocate(mach_task_self_, vm_address_t(bitPattern: info), vm_size_t(size) * 4) }
let numCores = Int(size) / 4
let p = min(performanceCoreCount, numCores)
let e = numCores - p
var curBusy: [UInt64] = []
var curIdle: [UInt64] = []
info.withMemoryRebound(to: UInt32.self, capacity: Int(size)) { ptr in
for i in 0..<numCores {
let base = i * 4
curBusy.append(UInt64(ptr[base]) + UInt64(ptr[base + 1]))
curIdle.append(UInt64(ptr[base + 2]))
}
}
let hasBaseline = previousBusy.count == numCores
if !hasBaseline {
previousBusy = curBusy
previousIdle = curIdle
return CPUData(performanceCoreValues: [], efficiencyCoreValues: [], performanceCoreCount: performanceCoreCount)
}
func deltaPcts(from start: Int, count: Int) -> [Int] {
guard count > 0 else { return [] }
return (start..<(start + count)).map { i in
let deltaBusy = curBusy[i] - previousBusy[i]
let deltaIdle = curIdle[i] - previousIdle[i]
let total = deltaBusy + deltaIdle
return total > 0 ? Int(deltaBusy * 100 / total) : 0
}
}
let pValues = deltaPcts(from: 0, count: p)
let eValues = deltaPcts(from: p, count: e)
previousBusy = curBusy
previousIdle = curIdle
return CPUData(performanceCoreValues: pValues, efficiencyCoreValues: eValues, performanceCoreCount: performanceCoreCount)
}
func sampleMemory() -> MemoryData {
var pressure: Int32 = 1
var psize = MemoryLayout<Int32>.size
sysctlbyname("kern.memorystatus_vm_pressure_level", &pressure, &psize, nil, 0)
let label: String
switch pressure {
case 4: label = "危急"
case 2: label = "警告"
default: label = "正常"
}
var size = mach_msg_type_number_t(MemoryLayout<vm_statistics64_data_t>.size / 4)
var stats = vm_statistics64_data_t()
guard host_statistics64(mach_host_self(), HOST_VM_INFO64,
withUnsafeMutablePointer(to: &stats) { ptr in
ptr.withMemoryRebound(to: integer_t.self, capacity: 1) { $0 }
},
&size) == KERN_SUCCESS else {
return MemoryData(wiredCompressedPercent: 0, appMemoryPercent: 0, cachedFilesPercent: 0, pressureLevel: Int(pressure), pressureLabel: label)
}
let pageSize = UInt64(vm_kernel_page_size)
let total = ProcessInfo.processInfo.physicalMemory
guard total > 0 else {
return MemoryData(wiredCompressedPercent: 0, appMemoryPercent: 0, cachedFilesPercent: 0, pressureLevel: Int(pressure), pressureLabel: label)
}
let wiredCompressed = UInt64(stats.wire_count + stats.compressor_page_count) * pageSize
let app = UInt64(stats.internal_page_count) * pageSize
let cached = UInt64(stats.external_page_count) * pageSize
return MemoryData(
wiredCompressedPercent: Int(wiredCompressed * 100 / total),
appMemoryPercent: Int(app * 100 / total),
cachedFilesPercent: Int(cached * 100 / total),
pressureLevel: Int(pressure),
pressureLabel: label
)
}
// MARK: Update
func update() {
DispatchQueue.global(qos: .utility).async { [weak self] in
guard let self else { return }
let cpu = sampleCPU()
let memory = sampleMemory()
DispatchQueue.main.async {
self.cpuView.cpuData = cpu
self.cpuView.memoryData = memory
self.cpuView.needsDisplay = true
if self.popover.isShown {
self.popoverController.update(cpu: cpu, memory: memory)
}
}
}
}
}
// MARK: - Entry Point
let app = NSApplication.shared
let delegate = AppDelegate()
if CommandLine.arguments.contains("--version") {
print("statbar 0.1.0")
exit(0)
}
app.delegate = delegate
app.run()