SPB Git

Repository Public

AppDelegate.swift 8.4 KB 162 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/App/AppDelegate.swift3// Description: AppKit integration: deep links (spchat://), notifications, global quick-chat hot key and floating panel, termination behaviour.4import AppKit5import Carbon.HIToolbox6import SwiftUI7import UserNotifications8import SPChatCore910/// `spchat://c/<conversation id>` opens a conversation; `spchat://new?text=…` opens a new one with the composer11/// pre-filled. A link never sends a message, never changes data, and anything else is ignored.12enum DeepLink: Equatable {13    case conversation(String)14    case new(text: String?)1516    init?(_ url: URL) {17        guard url.scheme?.lowercased() == "spchat" else { return nil }18        let parts = ([url.host ?? ""] + url.pathComponents).filter { !$0.isEmpty && $0 != "/" }19        switch parts.first {20        case "c", "conversation":21            guard parts.count == 2, parts[1].range(of: #"^conv_[a-z0-9]{1,40}$"#, options: .regularExpression) != nil else { return nil }22            self = .conversation(parts[1])23        case "new":24            let text = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "text" }?.value25            self = .new(text: text.map { String($0.prefix(20_000)) })26        default: return nil27        }28    }29}3031final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {32    static var environment: AppEnvironment?33    private var hotKey: GlobalHotKey?34    private var quickPanel: QuickChatPanel?35    private var observation: NSKeyValueObservation?3637    func applicationDidFinishLaunching(_ notification: Notification) {38        UNUserNotificationCenter.current().delegate = self39        NSWindow.allowsAutomaticWindowTabbing = true40        updateHotKey()41        // Launch guard: after a forced quit, window restoration can bring back no window at all. A regular launch always42        // ends with one main window on screen (unless the app lives in the menu bar by choice, or hosts unit tests).43        Task { @MainActor in44            try? await Task.sleep(for: .milliseconds(900))45            self.ensureMainWindow()46        }47        NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in Task { @MainActor in self?.updateHotKey() } }48    }4950    private var hasMainWindow: Bool { NSApp.windows.contains { $0.isVisible && $0.canBecomeMain && !($0 is NSPanel) } }5152    func ensureMainWindow() {53        guard let env = Self.environment, !env.options.isHostedTest, !hasMainWindow else { return }54        MainWindowOpener.open?()55        NSApp.activate(ignoringOtherApps: true)56    }5758    /// Clicking the Dock icon with no window open brings one back.59    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {60        if !hasMainWindow { MainWindowOpener.open?(); return false }61        return true62    }6364    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { !(Self.environment?.preferences.showMenuBarIcon ?? false) }65    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }6667    func application(_ application: NSApplication, open urls: [URL]) {68        guard let env = Self.environment else { return }69        // files dropped on the Dock icon (or « Ouvrir avec ») become attachments of a new conversation; nothing is sent70        let files = urls.filter(\.isFileURL)71        if !files.isEmpty { NSApp.activate(ignoringOtherApps: true); env.pendingFiles = files; if !hasMainWindow { MainWindowOpener.open?() } }72        for url in urls where !url.isFileURL {73            guard let link = DeepLink(url) else { continue }74            NSApp.activate(ignoringOtherApps: true)75            switch link {76            case .conversation(let id): env.open(conversationId: id)77            case .new(let text): env.pendingComposerText = text ?? ""78            }79        }80    }8182    // MARK: Notifications8384    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {85        let id = response.notification.request.content.userInfo["conversationId"] as? String86        await MainActor.run { NSApp.activate(ignoringOtherApps: true); if let id { Self.environment?.open(conversationId: id) } }87    }88    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { [] }8990    // MARK: Quick chat9192    private func updateHotKey() {93        let wanted = Self.environment?.preferences.quickChatHotKey ?? false94        if wanted, hotKey == nil { hotKey = GlobalHotKey(keyCode: UInt32(kVK_Space), modifiers: UInt32(optionKey | cmdKey)) { [weak self] in self?.toggleQuickChat() } }95        else if !wanted { hotKey = nil }96    }9798    func toggleQuickChat() {99        guard let env = Self.environment else { return }100        if quickPanel == nil { quickPanel = QuickChatPanel(env: env) }101        quickPanel?.toggle()102    }103}104105/// Posts « answer ready » notifications. Permission is requested the first time the owner enables the option.106final class CompletionNotifier {107    func requestAuthorization() async -> Bool { (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound])) ?? false }108    func post(title: String, body: String, conversationId: String) {109        let content = UNMutableNotificationContent()110        content.title = title; content.body = body; content.sound = .default; content.userInfo = ["conversationId": conversationId]111        UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "done-" + conversationId, content: content, trigger: nil))112    }113}114115/// System-wide hot key through Carbon's RegisterEventHotKey: needs no Accessibility or Input Monitoring permission.116final class GlobalHotKey {117    nonisolated(unsafe) private var ref: EventHotKeyRef?118    nonisolated(unsafe) private var handler: EventHandlerRef?119    private let action: () -> Void120    nonisolated(unsafe) private static var actions: [UInt32: () -> Void] = [:]121    private let id: UInt32122123    init(keyCode: UInt32, modifiers: UInt32, action: @escaping () -> Void) {124        self.action = action; id = UInt32.random(in: 1...UInt32.max)125        Self.actions[id] = action126        var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))127        InstallEventHandler(GetApplicationEventTarget(), { _, event, _ in128            var hk = EventHotKeyID()129            GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, MemoryLayout<EventHotKeyID>.size, nil, &hk)130            let key = hk.id131            DispatchQueue.main.async { MainActor.assumeIsolated { GlobalHotKey.fire(key) } }132            return noErr133        }, 1, &spec, nil, &handler)134        RegisterEventHotKey(keyCode, modifiers, EventHotKeyID(signature: OSType(0x53504348), id: id), GetApplicationEventTarget(), 0, &ref)135    }136    private static func fire(_ id: UInt32) { actions[id]?() }137    deinit { if let ref { UnregisterEventHotKey(ref) }; if let handler { RemoveEventHandler(handler) }; let id = id; DispatchQueue.main.async { GlobalHotKey.actions[id] = nil } }138}139140/// Floating quick-chat window (⌥⌘Space when enabled, or from the menu bar): type a question, read the answer, hand it141/// over to a full window.142final class QuickChatPanel {143    private let panel: NSPanel144    private let env: AppEnvironment145146    init(env: AppEnvironment) {147        self.env = env148        panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 560, height: 420), styleMask: [.titled, .closable, .resizable, .fullSizeContentView, .nonactivatingPanel], backing: .buffered, defer: true)149        panel.titleVisibility = .hidden; panel.titlebarAppearsTransparent = true; panel.isFloatingPanel = true; panel.level = .floating150        panel.hidesOnDeactivate = false; panel.isReleasedWhenClosed = false; panel.isMovableByWindowBackground = true151        panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]152        panel.contentView = NSHostingView(rootView: QuickChatView { [weak panel] in panel?.orderOut(nil) }.environment(env).tint(Palette.iris))153        panel.setFrameAutosaveName("SPChatQuickPanel")154    }155156    func toggle() {157        if panel.isVisible { panel.orderOut(nil); return }158        if panel.frame.origin == .zero { panel.center() }159        panel.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true)160    }161}162
Files main
Menu

Theme