-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathMenuBarView.swift
More file actions
510 lines (440 loc) · 17.1 KB
/
Copy pathMenuBarView.swift
File metadata and controls
510 lines (440 loc) · 17.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// MenuBarView.swift
// VocaMac
//
// The popover view shown when clicking the menu bar icon.
// Displays current status, audio level, last transcription, and quick actions.
import SwiftUI
// MARK: - Process Monitor
/// Polls the current process for CPU and memory usage every 5 seconds.
final class ProcessMonitor: ObservableObject {
@Published var cpuUsage: Double = 0 // percentage (0–100+)
@Published var memoryMB: Double = 0 // resident memory in MB
@Published var memoryPeakMB: Double = 0 // peak memory seen
@Published var threadCount: Int = 0 // active thread count
private var timer: Timer?
init() {
refresh()
timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
self?.refresh()
}
}
deinit { timer?.invalidate() }
func refresh() {
// --- Memory via mach_task_basic_info ---
var taskInfo = mach_task_basic_info()
var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
let kr = withUnsafeMutablePointer(to: &taskInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
}
}
if kr == KERN_SUCCESS {
let mb = Double(taskInfo.resident_size) / (1024 * 1024)
DispatchQueue.main.async {
self.memoryMB = mb
self.memoryPeakMB = max(self.memoryPeakMB, mb)
}
}
// --- CPU via task_threads + thread_basic_info ---
var threadList: thread_act_array_t?
var threadCount: mach_msg_type_number_t = 0
let threadKr = task_threads(mach_task_self_, &threadList, &threadCount)
guard threadKr == KERN_SUCCESS, let threads = threadList else { return }
var totalCPU: Double = 0
for i in 0..<Int(threadCount) {
var threadInfo = thread_basic_info()
var infoCount = mach_msg_type_number_t(MemoryLayout<thread_basic_info_data_t>.size / MemoryLayout<natural_t>.size)
let infoKr = withUnsafeMutablePointer(to: &threadInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(infoCount)) {
thread_info(threads[i], thread_flavor_t(THREAD_BASIC_INFO), $0, &infoCount)
}
}
if infoKr == KERN_SUCCESS && threadInfo.flags != TH_FLAGS_IDLE {
totalCPU += Double(threadInfo.cpu_usage) / Double(TH_USAGE_SCALE) * 100
}
}
let count2 = Int(threadCount)
// Deallocate the thread list
let size = vm_size_t(MemoryLayout<thread_t>.stride * Int(threadCount))
vm_deallocate(mach_task_self_, vm_address_t(bitPattern: threads), size)
DispatchQueue.main.async {
self.cpuUsage = totalCPU
self.threadCount = count2
}
}
}
struct MenuBarView: View {
@EnvironmentObject var appState: AppState
@ObservedObject var settingsManager: SettingsWindowManager
@StateObject private var processMonitor = ProcessMonitor()
var body: some View {
VStack(alignment: .leading, spacing: 14) {
// Header
headerSection
Divider()
// Status & Recording
statusSection
// Last Transcription
if let transcription = appState.lastTranscription {
Divider()
transcriptionSection(transcription)
}
// Permissions Warning
if appState.micPermission != .granted || appState.accessibilityPermission != .granted || appState.inputMonitoringPermission != .granted {
Divider()
permissionsSection
}
Divider()
// Quick Actions
actionsSection
}
.padding(20)
.frame(width: 380)
}
// MARK: - Header
private var headerSection: some View {
HStack {
Image(systemName: "mic.fill")
.font(.title)
.foregroundStyle(.blue)
VStack(alignment: .leading, spacing: 3) {
Text("VocaMac")
.font(.title3)
.fontWeight(.semibold)
if let model = appState.currentModel {
Text("Model: \(model.size.displayName)")
.font(.subheadline)
.foregroundStyle(.secondary)
} else if appState.whisperService.isModelLoaded {
Text("Model: \(appState.whisperService.loadedModelName ?? "Loaded")")
.font(.subheadline)
.foregroundStyle(.secondary)
} else {
Text("Loading model...")
.font(.subheadline)
.foregroundStyle(.orange)
}
}
Spacer()
// CPU & RAM usage display
HStack(spacing: 10) {
ResourceBadge(
icon: "cpu",
value: String(format: "%.0f%%", processMonitor.cpuUsage),
details: [
("CPU Usage", String(format: "%.1f%%", processMonitor.cpuUsage)),
("Threads", "\(processMonitor.threadCount)"),
("Cores", "\(ProcessInfo.processInfo.activeProcessorCount)"),
]
)
ResourceBadge(
icon: "memorychip",
value: formattedMemory(processMonitor.memoryMB),
details: [
("Resident", String(format: "%.1f MB", processMonitor.memoryMB)),
("Peak", String(format: "%.1f MB", processMonitor.memoryPeakMB)),
("System", "\(ProcessInfo.processInfo.physicalMemory / (1024 * 1024 * 1024)) GB"),
]
)
}
}
}
// MARK: - Status
private var statusSection: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Circle()
.fill(statusColor)
.frame(width: 10, height: 10)
Text(statusText)
.font(.body)
.fontWeight(.medium)
.foregroundStyle(statusColor)
Spacer()
Text(activationModeHint)
.font(.caption)
.foregroundStyle(.secondary)
}
// Audio level indicator (visible during recording)
if appState.appStatus == .recording {
AudioLevelView(level: appState.audioLevel)
.frame(height: 6)
}
// Processing indicator
if appState.appStatus == .processing {
ProgressView()
.controlSize(.small)
.frame(maxWidth: .infinity, alignment: .center)
}
}
}
// MARK: - Transcription
private func transcriptionSection(_ result: VocaTranscription) -> some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("Last Transcription")
.font(.subheadline)
.foregroundStyle(.secondary)
Spacer()
Button {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(result.text, forType: .string)
} label: {
Image(systemName: "doc.on.doc")
.font(.subheadline)
}
.buttonStyle(.plain)
.help("Copy to clipboard")
}
Text(result.text)
.font(.body)
.lineLimit(4)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(Color.secondary.opacity(0.1))
.cornerRadius(8)
HStack {
Text("\(String(format: "%.1f", result.audioLengthSeconds))s audio")
Text("•")
Text("\(String(format: "%.1f", result.duration))s to transcribe")
Text("•")
Text(result.detectedLanguage)
}
.font(.caption)
.foregroundStyle(.secondary)
}
}
// MARK: - Permissions
private var permissionsSection: some View {
VStack(alignment: .leading, spacing: 8) {
Text("Permissions Required")
.font(.subheadline)
.foregroundStyle(.orange)
if appState.micPermission != .granted {
permissionButton(
label: appState.micPermission == .denied ? "Open Microphone Settings" : "Grant Microphone Access",
icon: "mic.badge.xmark",
isDenied: appState.micPermission == .denied,
action: { appState.requestMicrophonePermission() }
)
Text(appState.micPermission == .denied
? "Denied. Enable in System Settings → Privacy & Security → Microphone."
: "Required to capture your voice for transcription.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
if appState.accessibilityPermission != .granted {
permissionButton(
label: "Grant Accessibility Access",
icon: "lock.shield",
isDenied: appState.accessibilityPermission == .denied,
action: { appState.requestAccessibilityPermission() }
)
Text("Required for global hotkeys and text injection. Opens System Settings.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
if appState.inputMonitoringPermission != .granted {
permissionButton(
label: "Grant Input Monitoring",
icon: "keyboard",
isDenied: appState.inputMonitoringPermission == .denied,
action: { appState.requestInputMonitoringPermission() }
)
Text("Required to detect hotkey presses system-wide. Enable VocaMac in the list.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
/// Reusable permission button that shows different styling for denied vs not determined
private func permissionButton(label: String, icon: String, isDenied: Bool, action: @escaping () -> Void) -> some View {
Button {
action()
} label: {
Label(label, systemImage: icon)
.font(.callout)
}
.buttonStyle(.plain)
.foregroundStyle(isDenied ? .red : .orange)
}
// MARK: - Actions
private var actionsSection: some View {
VStack(spacing: 2) {
Button {
settingsManager.open(appState: appState)
} label: {
HStack {
Image(systemName: "gear")
Text("Settings")
Spacer()
Text("⌘,")
.foregroundStyle(.secondary)
}
.font(.body)
.padding(.vertical, 6)
.padding(.horizontal, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.background(
RoundedRectangle(cornerRadius: 6)
.fill(Color.primary.opacity(0.0001))
)
}
.buttonStyle(MenuRowButtonStyle())
Button {
NSApplication.shared.terminate(nil)
} label: {
HStack {
Image(systemName: "power")
Text("Quit VocaMac")
Spacer()
Text("⌘Q")
.foregroundStyle(.secondary)
}
.font(.body)
.padding(.vertical, 6)
.padding(.horizontal, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.background(
RoundedRectangle(cornerRadius: 6)
.fill(Color.primary.opacity(0.0001))
)
}
.buttonStyle(MenuRowButtonStyle())
}
.padding(.horizontal, -8)
}
// MARK: - Helpers
private var statusText: String {
switch appState.appStatus {
case .idle: return "Ready"
case .recording: return "Recording..."
case .processing: return "Transcribing..."
case .error: return appState.errorMessage ?? "Error"
}
}
private var statusColor: Color {
switch appState.appStatus {
case .idle: return .green
case .recording: return .red
case .processing: return .orange
case .error: return .yellow
}
}
private var activationModeHint: String {
let keyName = KeyCodeReference.displayName(for: appState.hotKeyCode)
switch appState.activationMode {
case .pushToTalk:
return "Hold \(keyName)"
case .doubleTapToggle:
return "Double-tap \(keyName)"
}
}
/// Formats memory in MB to a compact human-readable string
private func formattedMemory(_ mb: Double) -> String {
if mb >= 1024 {
return String(format: "%.1f GB", mb / 1024)
}
return String(format: "%.0f MB", mb)
}
}
// MARK: - Menu Row Button Style
/// A button style that highlights on hover, matching native macOS menu behavior.
struct MenuRowButtonStyle: ButtonStyle {
@State private var isHovered = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(
RoundedRectangle(cornerRadius: 6)
.fill(isHovered ? Color.primary.opacity(0.1) : Color.clear)
)
.onHover { hovering in
isHovered = hovering
}
}
}
// MARK: - Resource Badge
/// A compact CPU/RAM badge that shows a detail popover on hover.
struct ResourceBadge: View {
let icon: String
let value: String
let details: [(String, String)]
@State private var isHovered = false
var body: some View {
HStack(spacing: 3) {
Image(systemName: icon)
.font(.caption2)
.foregroundStyle(.secondary)
Text(value)
.font(.caption)
.foregroundStyle(.secondary)
.monospacedDigit()
}
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(
RoundedRectangle(cornerRadius: 5)
.fill(isHovered ? Color.primary.opacity(0.08) : Color.clear)
)
.onHover { hovering in
withAnimation(.easeInOut(duration: 0.15)) {
isHovered = hovering
}
}
.popover(isPresented: $isHovered, arrowEdge: .bottom) {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 4) {
Image(systemName: icon)
.font(.subheadline)
.foregroundStyle(.blue)
Text(value)
.font(.subheadline)
.fontWeight(.semibold)
}
Divider()
ForEach(details, id: \.0) { label, val in
HStack {
Text(label)
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
Text(val)
.font(.caption)
.monospacedDigit()
}
}
}
.padding(10)
.frame(width: 160)
}
}
}
// MARK: - Audio Level View
/// A simple horizontal bar that visualizes the current audio input level
struct AudioLevelView: View {
let level: Float
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
// Background track
RoundedRectangle(cornerRadius: 2)
.fill(Color.secondary.opacity(0.2))
// Level indicator
RoundedRectangle(cornerRadius: 2)
.fill(levelColor)
.frame(width: max(0, geometry.size.width * CGFloat(level)))
.animation(.easeOut(duration: 0.1), value: level)
}
}
}
private var levelColor: Color {
if level > 0.8 { return .red }
if level > 0.5 { return .orange }
return .green
}
}