|
| 1 | +// |
| 2 | +// AppDelegate.swift |
| 3 | +// EchoX |
| 4 | +// |
| 5 | +// Main application delegate managing menubar, shortcuts, and recording indicator |
| 6 | +// |
| 7 | + |
| 8 | +import Cocoa |
| 9 | +import SwiftUI |
| 10 | +import Carbon.HIToolbox |
| 11 | +import AVFoundation |
| 12 | + |
| 13 | +class AppDelegate: NSObject, NSApplicationDelegate { |
| 14 | + var statusItem: NSStatusItem? |
| 15 | + var audioManager: AudioManager! |
| 16 | + var permissionManager: PermissionManager! |
| 17 | + var settingsWindow: NSWindow? |
| 18 | + var globalEventMonitor: Any? |
| 19 | + var localEventMonitor: Any? |
| 20 | + var recordingIndicator: RecordingIndicatorWindow? |
| 21 | + var permissionCheckTimer: Timer? |
| 22 | + var eventTapCreationFailed = false |
| 23 | + |
| 24 | + func applicationDidFinishLaunching(_ notification: Notification) { |
| 25 | + setupMenuBar() |
| 26 | + audioManager = AudioManager() |
| 27 | + permissionManager = PermissionManager() |
| 28 | + setupGlobalKeyboardShortcut() |
| 29 | + requestPermissions() |
| 30 | + |
| 31 | + // Start monitoring for accessibility permission changes |
| 32 | + if eventTapCreationFailed { |
| 33 | + startPermissionMonitoring() |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + func requestPermissions() { |
| 38 | + // Request microphone permission |
| 39 | + AVCaptureDevice.requestAccess(for: .audio) { granted in |
| 40 | + DispatchQueue.main.async { [weak self] in |
| 41 | + self?.permissionManager.microphoneStatus = granted ? .granted : .denied |
| 42 | + if !granted { |
| 43 | + self?.showPermissionAlert(for: "Microphone") |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Accessibility permission is checked automatically when creating event tap |
| 49 | + // If it fails, showAccessibilityAlert() will be called from setupGlobalKeyboardShortcut() |
| 50 | + permissionManager.checkAccessibilityPermission() |
| 51 | + } |
| 52 | + |
| 53 | + func showPermissionAlert(for permission: String) { |
| 54 | + let alert = NSAlert() |
| 55 | + alert.messageText = "\(permission) Permission Required" |
| 56 | + alert.informativeText = "EchoX needs \(permission.lowercased()) access to function properly. Please grant permission in System Settings." |
| 57 | + alert.alertStyle = .warning |
| 58 | + alert.addButton(withTitle: "Open Settings") |
| 59 | + alert.addButton(withTitle: "Later") |
| 60 | + |
| 61 | + let response = alert.runModal() |
| 62 | + if response == .alertFirstButtonReturn { |
| 63 | + permissionManager.openSystemPreferences(for: permission.lowercased()) |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + func setupMenuBar() { |
| 68 | + statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) |
| 69 | + |
| 70 | + if let button = statusItem?.button { |
| 71 | + button.image = NSImage(systemSymbolName: "waveform", accessibilityDescription: "EchoX") |
| 72 | + } |
| 73 | + |
| 74 | + let menu = NSMenu() |
| 75 | + |
| 76 | + menu.addItem(NSMenuItem(title: "Settings", action: #selector(openSettings), keyEquivalent: ",")) |
| 77 | + menu.addItem(NSMenuItem.separator()) |
| 78 | + menu.addItem(NSMenuItem(title: "Quit", action: #selector(quit), keyEquivalent: "q")) |
| 79 | + |
| 80 | + statusItem?.menu = menu |
| 81 | + } |
| 82 | + |
| 83 | + func setupGlobalKeyboardShortcut() { |
| 84 | + recordingIndicator = RecordingIndicatorWindow() |
| 85 | + |
| 86 | + let eventMask = CGEventMask(1 << CGEventType.keyDown.rawValue) | CGEventMask(1 << CGEventType.keyUp.rawValue) |
| 87 | + |
| 88 | + guard let eventTap = CGEvent.tapCreate( |
| 89 | + tap: .cgSessionEventTap, |
| 90 | + place: .headInsertEventTap, |
| 91 | + options: CGEventTapOptions(rawValue: 0)!, // Active filter (not passive listener) |
| 92 | + eventsOfInterest: eventMask, |
| 93 | + callback: { proxy, type, event, refcon in |
| 94 | + let appDelegate = Unmanaged<AppDelegate>.fromOpaque(refcon!).takeUnretainedValue() |
| 95 | + return appDelegate.handleGlobalKeyEvent(proxy: proxy, type: type, event: event) |
| 96 | + }, |
| 97 | + userInfo: Unmanaged.passUnretained(self).toOpaque() |
| 98 | + ) else { |
| 99 | + print("ERROR: Failed to create event tap. Grant Accessibility permission in System Settings.") |
| 100 | + // macOS will show its own system dialog automatically |
| 101 | + eventTapCreationFailed = true |
| 102 | + return |
| 103 | + } |
| 104 | + |
| 105 | + let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0) |
| 106 | + CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes) |
| 107 | + CGEvent.tapEnable(tap: eventTap, enable: true) |
| 108 | + |
| 109 | + print("Global keyboard shortcut enabled.") |
| 110 | + } |
| 111 | + |
| 112 | + func handleGlobalKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? { |
| 113 | + if type == .keyDown || type == .keyUp { |
| 114 | + let keyCode = UInt16(event.getIntegerValueField(.keyboardEventKeycode)) |
| 115 | + let flags = event.flags |
| 116 | + |
| 117 | + // Build required modifier flags |
| 118 | + var requiredModifiers: CGEventFlags = [] |
| 119 | + if audioManager.shortcutModifierFlags.contains(.command) { requiredModifiers.insert(.maskCommand) } |
| 120 | + if audioManager.shortcutModifierFlags.contains(.option) { requiredModifiers.insert(.maskAlternate) } |
| 121 | + if audioManager.shortcutModifierFlags.contains(.shift) { requiredModifiers.insert(.maskShift) } |
| 122 | + if audioManager.shortcutModifierFlags.contains(.control) { requiredModifiers.insert(.maskControl) } |
| 123 | + |
| 124 | + // Check if keyCode matches |
| 125 | + guard keyCode == audioManager.shortcutKeyCode else { |
| 126 | + return Unmanaged.passRetained(event) |
| 127 | + } |
| 128 | + |
| 129 | + // Extract only the modifier flags we care about from the event |
| 130 | + let relevantFlags = flags.intersection([.maskCommand, .maskAlternate, .maskShift, .maskControl]) |
| 131 | + |
| 132 | + // Check if modifiers match exactly |
| 133 | + guard relevantFlags == requiredModifiers else { |
| 134 | + return Unmanaged.passRetained(event) |
| 135 | + } |
| 136 | + |
| 137 | + // At this point, we have a match - consume the event completely |
| 138 | + let isRepeat = event.getIntegerValueField(.keyboardEventAutorepeat) == 1 |
| 139 | + |
| 140 | + DispatchQueue.main.async { [weak self] in |
| 141 | + if type == .keyDown && !isRepeat { |
| 142 | + print("✓ Shortcut matched - starting recording") |
| 143 | + self?.audioManager.startRecording() |
| 144 | + self?.recordingIndicator?.show() |
| 145 | + } else if type == .keyUp { |
| 146 | + print("✓ Shortcut released - stopping recording") |
| 147 | + self?.audioManager.stopRecordingAndPlayback() |
| 148 | + self?.recordingIndicator?.hide() |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + // Return nil to completely block this event from propagating |
| 153 | + return nil |
| 154 | + } |
| 155 | + |
| 156 | + return Unmanaged.passRetained(event) |
| 157 | + } |
| 158 | + |
| 159 | + |
| 160 | + @objc func openSettings() { |
| 161 | + if settingsWindow == nil { |
| 162 | + let settingsView = SettingsView( |
| 163 | + audioManager: audioManager, |
| 164 | + permissionManager: permissionManager, |
| 165 | + onClose: { [weak self] in |
| 166 | + self?.settingsWindow?.close() |
| 167 | + self?.settingsWindow = nil |
| 168 | + } |
| 169 | + ) |
| 170 | + let hostingController = NSHostingController(rootView: settingsView) |
| 171 | + |
| 172 | + settingsWindow = NSWindow(contentViewController: hostingController) |
| 173 | + settingsWindow?.title = "EchoX Settings" |
| 174 | + settingsWindow?.styleMask = [.titled, .closable] |
| 175 | + settingsWindow?.setContentSize(NSSize(width: 450, height: 500)) |
| 176 | + settingsWindow?.center() |
| 177 | + } |
| 178 | + |
| 179 | + permissionManager.refreshPermissions() |
| 180 | + settingsWindow?.makeKeyAndOrderFront(nil) |
| 181 | + NSApp.activate(ignoringOtherApps: true) |
| 182 | + } |
| 183 | + |
| 184 | + @objc func quit() { |
| 185 | + NSApplication.shared.terminate(nil) |
| 186 | + } |
| 187 | + |
| 188 | + // MARK: - Permission Monitoring |
| 189 | + |
| 190 | + func startPermissionMonitoring() { |
| 191 | + // Check every 1 second if accessibility permission has been granted |
| 192 | + permissionCheckTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in |
| 193 | + self?.checkAccessibilityPermissionAndRestart() |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + func checkAccessibilityPermissionAndRestart() { |
| 198 | + let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: false] |
| 199 | + let accessEnabled = AXIsProcessTrustedWithOptions(options) |
| 200 | + |
| 201 | + if accessEnabled { |
| 202 | + print("✓ Accessibility permission granted! Restarting app...") |
| 203 | + permissionCheckTimer?.invalidate() |
| 204 | + permissionCheckTimer = nil |
| 205 | + restartApp() |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + func restartApp() { |
| 210 | + let task = Process() |
| 211 | + task.launchPath = "/usr/bin/open" |
| 212 | + task.arguments = [Bundle.main.bundlePath] |
| 213 | + task.launch() |
| 214 | + |
| 215 | + NSApp.terminate(nil) |
| 216 | + } |
| 217 | +} |
0 commit comments