Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/AppDelegate.swift3// Description: AppKit integration: deep links (spnotes://), macOS Service "new note from selection", global quick-note hot key and floating panel, durable flush before termination.4import AppKit5import Carbon.HIToolbox6import SwiftUI7import CoreSpotlight8import SPNotesDocument910final class AppDelegate: NSObject, NSApplicationDelegate {11 static var environment: AppEnvironment?12 static private(set) weak var shared: AppDelegate?13 private var hotKey: GlobalHotKey?14 private var registered: HotKeyShortcut?15 private var quickPanel: QuickNotePanel?1617 func applicationWillFinishLaunching(_ notification: Notification) {18 // hosting unit tests: the process never shows a window and never takes the keyboard19 if Self.environment?.options.isHostedTest == true { NSApp.setActivationPolicy(.prohibited) }20 }2122 func applicationDidFinishLaunching(_ notification: Notification) {23 Self.shared = self24 NSWindow.allowsAutomaticWindowTabbing = true25 NSApp.servicesProvider = self26 updateHotKey()27 NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in Task { @MainActor in self?.updateHotKey() } }28 // Launch guard: after a forced quit, or a launch in the background, window restoration can bring back no window.29 Task { @MainActor in30 try? await Task.sleep(for: .milliseconds(900))31 guard let env = Self.environment, !env.options.isHostedTest else { return }32 #if DEBUG33 if env.options.noActivate {34 // Development screenshots: a launch in the background creates no SwiftUI window, and activating the app35 // would take the keyboard from whoever is using the Mac. The main view is hosted in a plain window that36 // is put on screen behind everything and never becomes key.37 let host = NSHostingController(rootView: MainWindow(initialNote: nil).environment(env))38 if env.options.route == "quicknote" { self.quickPanel = QuickNotePanel(env: env); self.quickPanel?.showForScreenshot(); return }39 if env.options.route == "settings" { // the settings in a real (background) window, tab bar included40 let s = NSWindow(contentViewController: NSHostingController(rootView: SettingsView().frame(height: 660).environment(env).preferredColorScheme(env.preferences.appearance.colorScheme)))41 s.styleMask = [.titled, .closable]; s.title = "Réglages"; s.isReleasedWhenClosed = false; s.setFrameOrigin(NSPoint(x: 40, y: 40)); s.order(.below, relativeTo: 0)42 self.benchWindow = s; return43 }44 host.sceneBridgingOptions = [.toolbars, .title]45 let w = NSWindow(contentViewController: host)46 w.styleMask = [.titled, .closable, .resizable, .miniaturizable, .fullSizeContentView]; w.setContentSize(NSSize(width: 1280, height: 800)); w.isReleasedWhenClosed = false47 w.setFrameOrigin(NSPoint(x: 40, y: 40)); w.order(.below, relativeTo: 0)48 self.benchWindow = w49 return50 }51 #endif52 if !self.hasMainWindow { MainWindowOpener.open?(); NSApp.activate(ignoringOtherApps: true) }53 }54 }55 private var benchWindow: NSWindow?5657 private var hasMainWindow: Bool { NSApp.windows.contains { $0.isVisible && $0.canBecomeMain && !($0 is NSPanel) } }58 func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { if !hasMainWindow { MainWindowOpener.open?(); return false }; return true }59 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { !(Self.environment?.preferences.showMenuBarIcon ?? false) && !(Self.environment?.preferences.quickNoteHotKey ?? false) }60 func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }6162 /// Nothing typed is left in memory when the application quits: every open note is written, then the database is checkpointed.63 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {64 guard let env = Self.environment, !env.options.isHostedTest, !env.isBlocked else { return .terminateNow }65 Task { @MainActor in66 await env.flushAll()67 try? await env.store.checkpoint()68 NSApp.reply(toApplicationShouldTerminate: true)69 }70 return .terminateLater71 }7273 func application(_ application: NSApplication, open urls: [URL]) { for url in urls { handle(url: url) } }7475 /// A file (imported as a note: Markdown, text, RTF) or a `spnotes://` link.76 func handle(url: URL) {77 guard let env = Self.environment, !env.isBlocked else { return }78 if url.isFileURL { Task { let ids = await Exporter(env: env).importFiles([url]); if let id = ids.last { env.open(noteId: id) } }; return }79 guard let link = DeepLink(url) else { return }80 switch link {81 case .page(let route): env.open(route)82 case .destination(let d): env.show(d)83 case .new(let text): Task { if let id = await env.library.newNote(content: text.map { t in NoteDocument(lines: t.components(separatedBy: "\n").map { Line.paragraph(text: $0) }) }) { env.open(noteId: id) } }84 }85 }8687 /// A note chosen in Spotlight (Core Spotlight hands the note id back).88 func application(_ application: NSApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([any NSUserActivityRestoring]) -> Void) -> Bool {89 guard userActivity.activityType == CSSearchableItemActionType, let id = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String, UUID(uuidString: id) != nil, let env = Self.environment, !env.isBlocked else { return false }90 if !hasMainWindow { MainWindowOpener.open?() }91 env.open(noteId: id.lowercased()); return true92 }9394 /// macOS Service: « Nouvelle note SP Notes avec la sélection ».95 @objc func newNoteFromSelection(_ pboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer<NSString>) {96 guard let text = pboard.string(forType: .string), !text.isEmpty, let env = Self.environment, !env.isBlocked else { return }97 Task { @MainActor in98 // the selection of any application, through the Services menu: no Accessibility permission involved99 let id = await QuickCapture(env: env).capture(text: String(text.prefix(200_000)), source: "sélection")100 if let id, env.preferences.quickNoteTarget == .notes { env.open(noteId: id) }101 }102 }103104 private func updateHotKey() {105 guard let env = Self.environment else { return }106 let wanted = env.preferences.quickNoteHotKey && !env.options.isHostedTest && !env.options.noActivate, shortcut = env.preferences.quickNoteShortcut107 if !wanted { hotKey = nil; registered = nil }108 else if registered != shortcut, shortcut.isValid { hotKey = nil; hotKey = GlobalHotKey(keyCode: shortcut.keyCode, modifiers: shortcut.carbonModifiers) { [weak self] in self?.toggleQuickNote() }; registered = shortcut }109 }110111 func toggleQuickNote() {112 guard let env = Self.environment, !env.lock.isLocked, !env.isBlocked else { NSApp.activate(ignoringOtherApps: true); return }113 if quickPanel == nil { quickPanel = QuickNotePanel(env: env) }114 quickPanel?.toggle()115 }116}117118/// System-wide hot key through Carbon's RegisterEventHotKey: needs no Accessibility or Input Monitoring permission.119final class GlobalHotKey {120 nonisolated(unsafe) private var ref: EventHotKeyRef?121 nonisolated(unsafe) private var handler: EventHandlerRef?122 nonisolated(unsafe) private static var actions: [UInt32: () -> Void] = [:]123 private let id: UInt32124125 init(keyCode: UInt32, modifiers: UInt32, action: @escaping () -> Void) {126 id = UInt32.random(in: 1...UInt32.max)127 Self.actions[id] = action128 var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))129 InstallEventHandler(GetApplicationEventTarget(), { _, event, _ in130 var hk = EventHotKeyID()131 GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, MemoryLayout<EventHotKeyID>.size, nil, &hk)132 let key = hk.id133 DispatchQueue.main.async { MainActor.assumeIsolated { GlobalHotKey.fire(key) } }134 return noErr135 }, 1, &spec, nil, &handler)136 RegisterEventHotKey(keyCode, modifiers, EventHotKeyID(signature: OSType(0x53504E54), id: id), GetApplicationEventTarget(), 0, &ref)137 }138 private static func fire(_ id: UInt32) { actions[id]?() }139 deinit { if let ref { UnregisterEventHotKey(ref) }; if let handler { RemoveEventHandler(handler) }; let id = id; DispatchQueue.main.async { GlobalHotKey.actions[id] = nil } }140}141142