| | |
| | | |
| | | @main |
| | | struct TagLauncherApp: App { |
| | | private static let singletonLockFile = TagLauncherProcessSingleton.acquireOrHandOffAndExit() |
| | | @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate |
| | | |
| | | init() { |
| | | _ = Self.singletonLockFile |
| | | } |
| | | |
| | | var body: some Scene { |
| | | Settings { |
| | |
| | | .commands { |
| | | CommandGroup(replacing: .systemServices) { } |
| | | CommandGroup(replacing: .appVisibility) { } |
| | | CommandGroup(replacing: .help) { } |
| | | } |
| | | } |
| | | } |
| | | |
| | | // MARK: - App Delegate (menubar + overlay window + hotkey) |
| | | |
| | | final class OverlayPanel: NSPanel { |
| | | override var canBecomeKey: Bool { true } |
| | | override var canBecomeMain: Bool { true } |
| | | } |
| | | |
| | | final class AppDelegate: NSObject, NSApplicationDelegate { |
| | | final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { |
| | | private static let showDockIconKey = "showDockIcon" |
| | | private static let statusItemAutosaveName = "com.apptag.launcher.statusItem" |
| | | private static let statusItemAutosaveName = AppIdentity.statusItemAutosaveName |
| | | private static let statusItemButtonIdentifier = NSUserInterfaceItemIdentifier("TagLauncherStatusItemButton") |
| | | private static let statusItemAccessibilityLabel = "TagLauncher" |
| | | private static let statusItemAccessibilityLabel = AppIdentity.displayName |
| | | private static let showAppListMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherShowAppListMenuItem") |
| | | private static let showAppListShortcutGlyphs = "⌥⇧␣" |
| | | private static let overlayDefaultLevel = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.maximumWindow))) |
| | | private static let overlayTextInputLevel = NSWindow.Level.modalPanel |
| | | private static let helpMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherHelpMenu") |
| | | private static let downloadHelpMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherDownloadHelpMenuItem") |
| | | private static let externalActivationNotification = Notification.Name("TagLauncherExternalActivationRequested") |
| | | private static let externalActivationObject = AppIdentity.bundleIdentifier |
| | | private static let launcherOverlayLevel = NSWindow.Level(rawValue: NSWindow.Level.mainMenu.rawValue - 1) |
| | | private static let overlayDefaultLevel = launcherOverlayLevel |
| | | private static let overlayTextInputLevel = launcherOverlayLevel |
| | | |
| | | private var statusItem: NSStatusItem? |
| | | private var overlayWindow: NSWindow? |
| | | private var overlayKeyMonitor: Any? |
| | | private var quickSearchLocalMouseMonitor: Any? |
| | | private var quickSearchExternalMouseMonitor: Any? |
| | | private var settingsWindow: NSWindow? // Track Settings window to keep it above overlay |
| | | private var hotkeyRef: EventHotKeyRef? |
| | | private var mainHotkeyRef: EventHotKeyRef? |
| | | private var quickSearchHotkeyRef: EventHotKeyRef? |
| | | private var hotkeyEventHandlerInstalled = false |
| | | private var isQuickSearchOpen = false |
| | | private var isModalInteractionActive = false |
| | | private var isInEditMode = false // Suppress auto-dismiss during editing |
| | | private var isEditingAppNote = false |
| | | private var isConfiguringApplicationMenu = false |
| | | private var lastShowDockIcon: Bool? |
| | | private var statusMenuScreenForNextOverlay: NSScreen? |
| | | private var suppressReopenUntil = Date.distantPast |
| | | |
| | | private lazy var overlayController = OverlayWindowController( |
| | | dependencies: OverlayWindowController.Dependencies( |
| | | shouldStageAsAccessory: { [weak self] in |
| | | self?.shouldStageOverlayAsAccessory ?? false |
| | | }, |
| | | isSettingsVisible: { [weak self] in |
| | | self?.isSettingsVisible ?? false |
| | | }, |
| | | settingsWindow: { [weak self] in |
| | | self?.settingsWindow |
| | | }, |
| | | canHideOverlay: { [weak self] in |
| | | self?.isInEditMode == false |
| | | }, |
| | | currentOverlayLevel: { [weak self] in |
| | | self?.currentOverlayLevel ?? Self.overlayDefaultLevel |
| | | }, |
| | | overlayLevel: { [weak self] initialQuickSearchSource in |
| | | self?.overlayLevel(initialQuickSearchSource: initialQuickSearchSource) ?? Self.overlayDefaultLevel |
| | | }, |
| | | makeContentView: { [weak self] initialQuickSearchSource in |
| | | DismissibleHostingView( |
| | | rootView: ContentView( |
| | | hideOverlay: { [weak self] in |
| | | self?.hideOverlay(force: true) |
| | | }, |
| | | initialQuickSearchSource: initialQuickSearchSource |
| | | ), |
| | | onBackdropTap: { [weak self] in |
| | | self?.hideOverlay() |
| | | } |
| | | ) |
| | | }, |
| | | handleOverlayKeyEvent: { [weak self] event in |
| | | self?.handleOverlayKeyEvent(event) ?? false |
| | | }, |
| | | installOverlayKeyMonitor: { [weak self] in |
| | | self?.installOverlayKeyMonitor() |
| | | }, |
| | | removeOverlayKeyMonitor: { [weak self] in |
| | | self?.removeOverlayKeyMonitor() |
| | | }, |
| | | removeQuickSearchMouseMonitor: { [weak self] in |
| | | self?.removeQuickSearchExternalMouseMonitor() |
| | | }, |
| | | detachSettingsWindow: { [weak self] window in |
| | | self?.detachSettingsWindow(window) |
| | | }, |
| | | prepareSettingsWindow: { [weak self] window in |
| | | self?.prepareSettingsWindow(window) |
| | | }, |
| | | refreshChromeState: { [weak self] activate, avoidSpaceSwitch in |
| | | self?.refreshLauncherChromeState(activate: activate, avoidSpaceSwitch: avoidSpaceSwitch) |
| | | }, |
| | | onWillHide: { |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | }, |
| | | onDidHide: { |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidHide, object: nil) |
| | | }, |
| | | onDidShow: { |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidShow, object: nil) |
| | | } |
| | | ) |
| | | ) |
| | | |
| | | private var overlayWindow: NSWindow? { |
| | | overlayController.window |
| | | } |
| | | |
| | | private var overlayGeneration: Int { |
| | | overlayController.generation |
| | | } |
| | | |
| | | private var overlayAvoidsSpaceSwitch: Bool { |
| | | get { overlayController.avoidsSpaceSwitch } |
| | | set { overlayController.avoidsSpaceSwitch = newValue } |
| | | } |
| | | |
| | | private var isOverlayVisible: Bool { |
| | | overlayWindow?.isVisible == true |
| | | } |
| | | |
| | | private var isSettingsVisible: Bool { |
| | | settingsWindow?.isVisible == true |
| | | } |
| | | |
| | | private var requiresForegroundOwnership: Bool { |
| | | isOverlayVisible || isSettingsVisible |
| | | } |
| | | |
| | | private var shouldStageOverlayAsAccessory: Bool { |
| | | !isSettingsVisible && !UserDefaults.standard.bool(forKey: Self.showDockIconKey) |
| | | } |
| | | |
| | | private var currentOverlayLevel: NSWindow.Level { |
| | | if isEditingAppNote || isQuickSearchOpen { |
| | | return Self.overlayTextInputLevel |
| | | } |
| | | return Self.overlayDefaultLevel |
| | | } |
| | | |
| | | private func overlayLevel(initialQuickSearchSource: String? = nil) -> NSWindow.Level { |
| | | if initialQuickSearchSource != nil { |
| | | return Self.overlayTextInputLevel |
| | | } |
| | | return currentOverlayLevel |
| | | } |
| | | |
| | | static func refreshChromeSettings() { |
| | | (NSApp.delegate as? AppDelegate)?.syncChromeSettings(force: true) |
| | |
| | | migrateDefaultGroupName() |
| | | TagDatabase.seedDefaultTags() |
| | | syncChromeSettings(force: true) |
| | | registerHotkey() |
| | | observeHotkeyStatusChanges() |
| | | registerConfiguredHotkeys() |
| | | observeOtherWindows() |
| | | observeSettingsClose() |
| | | observeEditMode() |
| | | observeAppNoteEditing() |
| | | observeQuickSearch() |
| | | observePreferencesRequests() |
| | | observeExternalActivationRequests() |
| | | observeApplicationMenuChanges() |
| | | observeChromeSettings() |
| | | observeLanguageChanges() |
| | | setupLaunchAtLogin() |
| | | configureApplicationMenuWhenAvailable() |
| | | suppressReopenUntil = Date().addingTimeInterval(1.0) |
| | | configureApplicationMenuWhenAvailable(retries: 200) |
| | | } |
| | | |
| | | func applicationDidBecomeActive(_ notification: Notification) { |
| | | configureApplicationMenuWhenAvailable(retries: 12) |
| | | } |
| | | |
| | | /// Dock icon click → show overlay (same as menubar "Show TagLauncher") |
| | | func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { |
| | | showOverlay() |
| | | guard Date() >= suppressReopenUntil else { return false } |
| | | showOrFocusOverlay() |
| | | return false // Suppress default "unhide all windows" behavior |
| | | } |
| | | |
| | | func applicationWillTerminate(_ notification: Notification) { |
| | | hideOverlay(force: true, discardWindow: true) |
| | | unregisterHotkey(for: .main) |
| | | unregisterHotkey(for: .quickSearch) |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | removeOverlayKeyMonitor() |
| | | removeQuickSearchExternalMouseMonitor() |
| | | DistributedNotificationCenter.default().removeObserver( |
| | | self, |
| | | name: Self.externalActivationNotification, |
| | | object: Self.externalActivationObject |
| | | ) |
| | | } |
| | | |
| | | /// Ensure defaultGroupName is always the language-neutral key "Other". |
| | |
| | | let dockChanged = lastShowDockIcon != showDock |
| | | |
| | | if force || dockChanged { |
| | | NSApp.setActivationPolicy(showDock ? .regular : .accessory) |
| | | lastShowDockIcon = showDock |
| | | refreshLauncherChromeState() |
| | | } |
| | | |
| | | if force { |
| | | setupMenuBar() |
| | | } |
| | | } |
| | | |
| | | private func beginLauncherForegroundOwnership(activate: Bool = true, keyWindow: NSWindow? = nil) { |
| | | if NSApp.activationPolicy() != .regular { |
| | | NSApp.setActivationPolicy(.regular) |
| | | } |
| | | if activate { |
| | | claimLauncherForeground(keyWindow: keyWindow) |
| | | } |
| | | } |
| | | |
| | | private func claimLauncherForeground( |
| | | keyWindow: NSWindow? = nil, |
| | | retries: Int = 0, |
| | | overlayGeneration expectedOverlayGeneration: Int? = nil |
| | | ) { |
| | | if NSApp.activationPolicy() != .regular { |
| | | NSApp.setActivationPolicy(.regular) |
| | | } |
| | | |
| | | if isOverlayVisible && !NSApp.presentationOptions.contains(.hideDock) { |
| | | NSApp.presentationOptions = [.hideDock] |
| | | } |
| | | |
| | | NSApp.unhide(nil) |
| | | NSApp.activate(ignoringOtherApps: true) |
| | | |
| | | if let keyWindow, keyWindow.isVisible { |
| | | keyWindow.makeKeyAndOrderFront(nil) |
| | | keyWindow.makeMain() |
| | | keyWindow.orderFrontRegardless() |
| | | } |
| | | configureApplicationMenuWhenAvailable(retries: 4) |
| | | |
| | | let overlayShouldYieldToSettings = keyWindow == overlayWindow && isSettingsVisible |
| | | let keyWindowStillNeedsFocus = !overlayShouldYieldToSettings |
| | | && keyWindow?.isVisible == true |
| | | && keyWindow?.isKeyWindow == false |
| | | let shouldRetry = !NSApp.isActive |
| | | || !NSApp.presentationOptions.contains(.hideDock) |
| | | || keyWindowStillNeedsFocus |
| | | guard retries > 0, isOverlayVisible else { return } |
| | | guard shouldRetry else { return } |
| | | |
| | | let retryWindow = keyWindow |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) { [weak self] in |
| | | guard let self, self.isOverlayVisible else { return } |
| | | if let expectedOverlayGeneration, |
| | | expectedOverlayGeneration != self.overlayGeneration { |
| | | return |
| | | } |
| | | self.refreshLauncherChromeState() |
| | | self.claimLauncherForeground( |
| | | keyWindow: retryWindow, |
| | | retries: retries - 1, |
| | | overlayGeneration: expectedOverlayGeneration |
| | | ) |
| | | } |
| | | } |
| | | |
| | | private func refreshLauncherChromeState(activate: Bool = false, avoidSpaceSwitch: Bool = false) { |
| | | let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey) |
| | | lastShowDockIcon = showDock |
| | | |
| | | let shouldStayAccessoryForCurrentFullscreenSpace = isOverlayVisible |
| | | && (avoidSpaceSwitch || overlayAvoidsSpaceSwitch) |
| | | let desiredPolicy: NSApplication.ActivationPolicy = shouldStayAccessoryForCurrentFullscreenSpace |
| | | ? .accessory |
| | | : (requiresForegroundOwnership |
| | | ? .regular |
| | | : (showDock ? .regular : .accessory)) |
| | | if NSApp.activationPolicy() != desiredPolicy { |
| | | NSApp.setActivationPolicy(desiredPolicy) |
| | | } |
| | | |
| | | let desiredPresentation: NSApplication.PresentationOptions = isOverlayVisible ? [.hideDock] : [] |
| | | if NSApp.presentationOptions != desiredPresentation { |
| | | NSApp.presentationOptions = desiredPresentation |
| | | } |
| | | |
| | | if activate && requiresForegroundOwnership && !shouldStayAccessoryForCurrentFullscreenSpace { |
| | | let keyWindow = isSettingsVisible ? settingsWindow : (isOverlayVisible ? overlayWindow : nil) |
| | | claimLauncherForeground( |
| | | keyWindow: keyWindow, |
| | | retries: isOverlayVisible && !isSettingsVisible ? 5 : 0, |
| | | overlayGeneration: isOverlayVisible ? overlayGeneration : nil |
| | | ) |
| | | } |
| | | } |
| | | |
| | | private func handleApplicationDidResignActive() { |
| | | guard !isOverlayVisible else { |
| | | return |
| | | } |
| | | |
| | | if isQuickSearchOpen { |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | } |
| | | |
| | | if !requiresForegroundOwnership { |
| | | refreshLauncherChromeState() |
| | | } |
| | | } |
| | | |
| | |
| | | |
| | | // MARK: - Launch at Login (LaunchAgent, zero permissions) |
| | | |
| | | private static let launchAgentLabel = "com.apptag.launcher" |
| | | private static let launchAgentLabel = AppIdentity.launchAgentLabel |
| | | static var supportsLaunchAtLogin: Bool { |
| | | ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] == nil |
| | | } |
| | |
| | | guard supportsLaunchAtLogin else { return } |
| | | let plist: [String: Any] = [ |
| | | "Label": Self.launchAgentLabel, |
| | | "ProgramArguments": ["open", Bundle.main.bundlePath, "--hide"], |
| | | "ProgramArguments": Self.expectedLaunchAgentProgramArguments(), |
| | | "RunAtLoad": true, |
| | | ] |
| | | let dir = Self.launchAgentURL.deletingLastPathComponent() |
| | |
| | | (plist as NSDictionary).write(to: Self.launchAgentURL, atomically: true) |
| | | |
| | | let uid = getuid() |
| | | let bootoutTask = Process() |
| | | bootoutTask.launchPath = "/bin/launchctl" |
| | | bootoutTask.arguments = ["bootout", "gui/\(uid)/\(Self.launchAgentLabel)"] |
| | | try? bootoutTask.run() |
| | | bootoutTask.waitUntilExit() |
| | | |
| | | let task = Process() |
| | | task.launchPath = "/bin/launchctl" |
| | | task.arguments = ["bootstrap", "gui/\(uid)", Self.launchAgentURL.path] |
| | | task.launch() |
| | | try? task.run() |
| | | } |
| | | |
| | | static func disableLaunchAtLogin() { |
| | |
| | | let task = Process() |
| | | task.launchPath = "/bin/launchctl" |
| | | task.arguments = ["bootout", "gui/\(uid)/\(Self.launchAgentLabel)"] |
| | | task.launch() |
| | | try? task.run() |
| | | try? FileManager.default.removeItem(at: Self.launchAgentURL) |
| | | } |
| | | |
| | | private static func launchAgentProgramArguments() -> [String]? { |
| | | guard let plist = NSDictionary(contentsOf: Self.launchAgentURL) as? [String: Any] else { |
| | | return nil |
| | | } |
| | | return plist["ProgramArguments"] as? [String] |
| | | } |
| | | |
| | | private static func expectedLaunchAgentProgramArguments() -> [String] { |
| | | let executablePath = Bundle.main.executablePath |
| | | ?? Bundle.main.bundleURL |
| | | .appendingPathComponent("Contents/MacOS/\(AppIdentity.displayName)") |
| | | .path |
| | | return [executablePath, "--hide"] |
| | | } |
| | | |
| | | /// On first launch, enable login item by default via LaunchAgent. |
| | |
| | | return |
| | | } |
| | | let key = "launchAtLogin" |
| | | if !AppDefaults.hasStoredValue(for: key) && UserDefaults.standard.bool(forKey: key) { |
| | | guard UserDefaults.standard.bool(forKey: key) else { |
| | | Self.disableLaunchAtLogin() |
| | | return |
| | | } |
| | | |
| | | let expectedArguments = Self.expectedLaunchAgentProgramArguments() |
| | | if !AppDefaults.hasStoredValue(for: key) |
| | | || Self.launchAgentProgramArguments() != expectedArguments { |
| | | Self.enableLaunchAtLogin() |
| | | } |
| | | } |
| | |
| | | button.imageScaling = .scaleProportionallyDown |
| | | button.imagePosition = .imageOnly |
| | | button.toolTip = "TagLauncher — Tag-based app launcher" |
| | | button.action = #selector(toggleOverlay) |
| | | button.action = #selector(toggleOverlay(_:)) |
| | | button.target = self |
| | | } |
| | | |
| | | let menu = NSMenu() |
| | | menu.delegate = self |
| | | let showItem = NSMenuItem( |
| | | title: showAppListMenuTitle, |
| | | action: #selector(toggleOverlay), |
| | | action: #selector(toggleOverlayFromStatusMenu(_:)), |
| | | keyEquivalent: "" |
| | | ) |
| | | showItem.target = self |
| | |
| | | menu.addItem(.separator()) |
| | | let prefsItem = NSMenuItem( |
| | | title: tr("menu.preferences"), |
| | | action: #selector(openPreferences), |
| | | action: #selector(openPreferences(_:)), |
| | | keyEquivalent: "," |
| | | ) |
| | | prefsItem.target = self |
| | |
| | | ) |
| | | ) |
| | | statusItem.menu = menu |
| | | } |
| | | |
| | | func menuWillOpen(_ menu: NSMenu) { |
| | | statusMenuScreenForNextOverlay = overlayController.screenContainingCurrentPointer() |
| | | ?? statusItem?.button?.window?.screen |
| | | ?? NSScreen.main |
| | | ?? NSScreen.screens.first |
| | | } |
| | | |
| | | func menuDidClose(_ menu: NSMenu) { |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in |
| | | self?.statusMenuScreenForNextOverlay = nil |
| | | } |
| | | } |
| | | |
| | | private func makeMenuBarIcon() -> NSImage { |
| | |
| | | } |
| | | |
| | | private var showAppListMenuTitle: String { |
| | | "\(tr("menu.showAppList")) \(Self.showAppListShortcutGlyphs)" |
| | | if LauncherHotkeyRegistrationStore.state(for: .main) == .failed { |
| | | return tr("menu.showShortcutUnavailable") |
| | | } |
| | | return "\(tr("menu.showAppList")) \(LauncherHotkey.main.displayString)" |
| | | } |
| | | |
| | | private func observeApplicationMenuChanges() { |
| | |
| | | } |
| | | |
| | | self.configureApplicationMenu() |
| | | self.configureHelpMenu() |
| | | if retries > 0 && self.applicationMenuNeedsCleanup() { |
| | | self.configureApplicationMenuWhenAvailable(retries: retries - 1) |
| | | } |
| | |
| | | |
| | | private func configureShowAppListItem(_ item: NSMenuItem) { |
| | | item.title = showAppListMenuTitle |
| | | item.action = #selector(toggleOverlay) |
| | | item.action = #selector(toggleOverlayFromStatusMenu(_:)) |
| | | item.target = self |
| | | item.keyEquivalent = "" |
| | | item.keyEquivalentModifierMask = [] |
| | |
| | | } |
| | | |
| | | item.title = tr("menu.preferences") |
| | | item.action = #selector(openPreferences) |
| | | item.action = #selector(openPreferences(_:)) |
| | | item.target = self |
| | | item.keyEquivalent = "," |
| | | item.keyEquivalentModifierMask = .command |
| | |
| | | |
| | | private func isSettingsMenuItem(_ item: NSMenuItem) -> Bool { |
| | | item.action == Selector(("showSettingsWindow:")) |
| | | || item.action == #selector(openPreferences) |
| | | || item.action == #selector(openPreferences(_:)) |
| | | || item.title == tr("menu.preferences") |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | private func configureHelpMenu() { |
| | | guard let mainMenu = NSApp.mainMenu else { return } |
| | | NSApp.helpMenu = nil |
| | | |
| | | for item in mainMenu.items.reversed() { |
| | | let isHelpMenu = item.identifier == Self.helpMenuItemIdentifier |
| | | || item.title.localizedCaseInsensitiveContains("help") |
| | | || item.title == tr("menu.help") |
| | | || item.submenu?.title.localizedCaseInsensitiveContains("help") == true |
| | | || item.submenu?.title == tr("menu.help") |
| | | if isHelpMenu { |
| | | mainMenu.removeItem(item) |
| | | } |
| | | } |
| | | |
| | | let menuItem = NSMenuItem(title: tr("menu.help"), action: nil, keyEquivalent: "") |
| | | let helpMenu = NSMenu(title: tr("menu.help")) |
| | | menuItem.identifier = Self.helpMenuItemIdentifier |
| | | menuItem.submenu = helpMenu |
| | | |
| | | let downloadItem = NSMenuItem() |
| | | downloadItem.identifier = Self.downloadHelpMenuItemIdentifier |
| | | downloadItem.title = tr("help.downloadPDF") |
| | | downloadItem.action = #selector(openLocalizedHelp(_:)) |
| | | downloadItem.target = self |
| | | downloadItem.keyEquivalent = "" |
| | | downloadItem.keyEquivalentModifierMask = [] |
| | | downloadItem.isEnabled = true |
| | | helpMenu.addItem(downloadItem) |
| | | mainMenu.addItem(menuItem) |
| | | } |
| | | |
| | | @objc private func openLocalizedHelp(_ sender: Any? = nil) { |
| | | NSWorkspace.shared.open(HelpDocument.currentURL) |
| | | } |
| | | |
| | | private func removeMenuBarItem() { |
| | | guard let statusItem else { return } |
| | | NSStatusBar.system.removeStatusItem(statusItem) |
| | |
| | | |
| | | // MARK: - Overlay Window |
| | | |
| | | @objc private func toggleOverlay() { |
| | | if overlayWindow?.isVisible == true { |
| | | hideOverlay() |
| | | } else { |
| | | showOverlay() |
| | | @objc func toggleOverlay(_ sender: Any) { |
| | | performToggleOverlay(preferredScreen: nil) |
| | | } |
| | | |
| | | @objc func toggleOverlayFromStatusMenu(_ sender: Any) { |
| | | let preferredScreen = statusMenuScreenForNextOverlay |
| | | statusMenuScreenForNextOverlay = nil |
| | | DispatchQueue.main.async { [weak self] in |
| | | self?.performToggleOverlay(preferredScreen: preferredScreen) |
| | | } |
| | | } |
| | | |
| | | private func showOverlay() { |
| | | // Use the screen under the mouse cursor — works in fullscreen spaces |
| | | let mousePoint = NSEvent.mouseLocation |
| | | guard let screen = NSScreen.screens.first(where: { |
| | | NSMouseInRect(mousePoint, $0.frame, false) |
| | | }) ?? NSScreen.main ?? NSScreen.screens.first else { return } |
| | | private func performToggleOverlay(preferredScreen: NSScreen?) { |
| | | overlayController.toggle(preferredScreen: preferredScreen) |
| | | } |
| | | |
| | | let window: NSWindow |
| | | if let existingWindow = overlayWindow { |
| | | window = existingWindow |
| | | } else { |
| | | window = makeOverlayWindow(on: screen) |
| | | overlayWindow = window |
| | | } |
| | | private func showOrFocusOverlay(preferredScreen: NSScreen? = nil) { |
| | | overlayController.showOrFocus(preferredScreen: preferredScreen) |
| | | } |
| | | |
| | | window.setFrame(screen.frame, display: true) |
| | | window.level = isEditingAppNote ? Self.overlayTextInputLevel : Self.overlayDefaultLevel |
| | | |
| | | installOverlayKeyMonitor() |
| | | |
| | | window.makeKeyAndOrderFront(nil) |
| | | window.orderFrontRegardless() |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidShow, object: nil) |
| | | private func showOverlay( |
| | | initialQuickSearchSource: String? = nil, |
| | | preferredScreen: NSScreen? = nil, |
| | | stagedForAllSpaces: Bool = false |
| | | ) { |
| | | overlayController.show( |
| | | initialQuickSearchSource: initialQuickSearchSource, |
| | | preferredScreen: preferredScreen, |
| | | stagedForAllSpaces: stagedForAllSpaces |
| | | ) |
| | | } |
| | | |
| | | private func installOverlayKeyMonitor() { |
| | | guard overlayKeyMonitor == nil else { return } |
| | | overlayKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in |
| | | if event.keyCode == 53 { // Escape |
| | | self?.hideOverlay() |
| | | guard let self else { return event } |
| | | if self.handleOverlayKeyEvent(event) { |
| | | return nil |
| | | } |
| | | return event |
| | | } |
| | | } |
| | | |
| | | @discardableResult |
| | | private func handleOverlayKeyEvent(_ event: NSEvent) -> Bool { |
| | | guard event.type == .keyDown, |
| | | shouldHandleOverlayKeyEvent(event) |
| | | else { return false } |
| | | |
| | | if event.keyCode == UInt16(kVK_Escape) { |
| | | return handleOverlayEscapeKey() |
| | | } |
| | | if shouldOpenQuickSearch(for: event) { |
| | | requestQuickSearch(source: QuickSearchOpenSource.mainOverlay) |
| | | return true |
| | | } |
| | | return false |
| | | } |
| | | |
| | | private func handleOverlayEscapeKey() -> Bool { |
| | | if isQuickSearchOpen { |
| | | isQuickSearchOpen = false |
| | | removeQuickSearchExternalMouseMonitor() |
| | | updateOverlayLevelForTextInput() |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | return true |
| | | } |
| | | guard !isSettingsVisible, |
| | | !isEditingAppNote, |
| | | !isModalInteractionActive |
| | | else { return false } |
| | | hideOverlay(force: true) |
| | | return true |
| | | } |
| | | |
| | | private func requestQuickSearch(source: String) { |
| | | isQuickSearchOpen = true |
| | | promoteOverlayToForegroundInput() |
| | | updateOverlayLevelForTextInput() |
| | | installQuickSearchExternalMouseMonitor() |
| | | DispatchQueue.main.async { |
| | | NotificationCenter.default.post( |
| | | name: .tagLauncherQuickSearchRequested, |
| | | object: nil, |
| | | userInfo: ["source": source] |
| | | ) |
| | | } |
| | | } |
| | | |
| | | private func shouldHandleOverlayKeyEvent(_ event: NSEvent) -> Bool { |
| | | guard overlayWindow?.isVisible == true else { return false } |
| | | if !isSettingsVisible && NSApp.isActive { |
| | | return true |
| | | } |
| | | if event.window == overlayWindow { return true } |
| | | return event.window == nil && NSApp.keyWindow == overlayWindow |
| | | } |
| | | |
| | | private func shouldOpenQuickSearch(for event: NSEvent) -> Bool { |
| | | guard event.keyCode == UInt16(kVK_Space), |
| | | !event.isARepeat, |
| | | event.modifierFlags.intersection(.deviceIndependentFlagsMask).isEmpty, |
| | | overlayWindow?.isVisible == true, |
| | | !isQuickSearchOpen, |
| | | !isInEditMode, |
| | | !isEditingAppNote, |
| | | !isModalInteractionActive |
| | | else { return false } |
| | | |
| | | return true |
| | | } |
| | | |
| | | private func removeOverlayKeyMonitor() { |
| | |
| | | } |
| | | } |
| | | |
| | | private func makeOverlayWindow(on screen: NSScreen) -> NSWindow { |
| | | let panel = OverlayPanel( |
| | | contentRect: screen.frame, |
| | | styleMask: [.borderless, .fullSizeContentView, .nonactivatingPanel], |
| | | backing: .buffered, |
| | | defer: false |
| | | ) |
| | | panel.isFloatingPanel = true |
| | | panel.hidesOnDeactivate = false |
| | | panel.collectionBehavior = [ |
| | | .moveToActiveSpace, |
| | | .fullScreenAuxiliary, |
| | | .stationary, |
| | | .transient, |
| | | .ignoresCycle |
| | | ] |
| | | panel.isOpaque = false |
| | | panel.backgroundColor = .clear |
| | | panel.hasShadow = false |
| | | panel.titlebarAppearsTransparent = true |
| | | panel.titleVisibility = .hidden |
| | | panel.isReleasedWhenClosed = false |
| | | panel.contentView = DismissibleHostingView( |
| | | rootView: ContentView(hideOverlay: { [weak self] in |
| | | self?.hideOverlay(force: true) |
| | | }), |
| | | onBackdropTap: { [weak self] in |
| | | self?.hideOverlay() |
| | | } |
| | | ) |
| | | return panel |
| | | private func hideOverlay(force: Bool = false, discardWindow: Bool = false) { |
| | | overlayController.hide(force: force, discardWindow: discardWindow) |
| | | } |
| | | |
| | | private func hideOverlay(force: Bool = false) { |
| | | guard force || !isInEditMode else { return } |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | if let settingsWindow, settingsWindow.parent == overlayWindow { |
| | | detachSettingsWindow(settingsWindow) |
| | | } |
| | | overlayWindow?.orderOut(nil) |
| | | removeOverlayKeyMonitor() |
| | | if force { |
| | | overlayWindow = nil |
| | | } |
| | | // MARK: - Global Hotkeys |
| | | |
| | | private func registerConfiguredHotkeys() { |
| | | installHotkeyEventHandlerIfNeeded() |
| | | registerFixedHotkey(.main) |
| | | registerFixedHotkey(.quickSearch) |
| | | } |
| | | |
| | | // MARK: - Global Hotkey (Shift+Option+Space) |
| | | private func registerFixedHotkey(_ kind: LauncherHotkeyKind) { |
| | | unregisterHotkey(for: kind) |
| | | let hotkey = kind.hotkey |
| | | |
| | | /// Carbon RegisterEventHotKey. If it fails (sandbox, etc.), falls back to menu bar only. |
| | | private func registerHotkey() { |
| | | var hotkeyID = EventHotKeyID() |
| | | hotkeyID.signature = OSType(0x41505447) // 'APTG' |
| | | hotkeyID.id = 1 |
| | | hotkeyID.id = kind.eventID |
| | | |
| | | let modifiers = UInt32(shiftKey | optionKey) |
| | | |
| | | var ref: EventHotKeyRef? |
| | | var newRef: EventHotKeyRef? |
| | | let status = RegisterEventHotKey( |
| | | UInt32(kVK_Space), |
| | | modifiers, |
| | | hotkey.keyCode, |
| | | hotkey.modifiers, |
| | | hotkeyID, |
| | | GetApplicationEventTarget(), |
| | | 0, |
| | | &ref |
| | | &newRef |
| | | ) |
| | | hotkeyRef = ref |
| | | |
| | | if status != noErr { |
| | | print("[TagLauncher] Hotkey registration failed: \(status). Falling back to menu bar only.") |
| | | return |
| | | if status == noErr, let newRef { |
| | | setHotkeyRef(newRef, for: kind) |
| | | LauncherHotkeyRegistrationStore.setActive(for: kind) |
| | | } else { |
| | | setHotkeyRef(nil, for: kind) |
| | | LauncherHotkeyRegistrationStore.setFailed(status, for: kind) |
| | | print("[TagLauncher] Fixed hotkey registration failed for \(kind.rawValue): \(status)") |
| | | } |
| | | } |
| | | |
| | | private func observeHotkeyStatusChanges() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherHotkeyRegistrationChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] _ in |
| | | self?.setupMenuBar() |
| | | self?.configureApplicationMenuWhenAvailable(retries: 2) |
| | | } |
| | | } |
| | | |
| | | private func installHotkeyEventHandlerIfNeeded() { |
| | | guard !hotkeyEventHandlerInstalled else { return } |
| | | hotkeyEventHandlerInstalled = true |
| | | |
| | | var eventSpec = EventTypeSpec( |
| | | eventClass: OSType(kEventClassKeyboard), |
| | | eventKind: UInt32(kEventHotKeyPressed) |
| | | ) |
| | | |
| | | let selfPtr = Unmanaged.passUnretained(self).toOpaque() |
| | | |
| | | InstallEventHandler( |
| | | GetApplicationEventTarget(), |
| | | { (_, _, userData) -> OSStatus in |
| | | guard let userData else { return noErr } |
| | | { (_, event, userData) -> OSStatus in |
| | | guard let event, let userData else { return noErr } |
| | | var hotkeyID = EventHotKeyID() |
| | | let status = GetEventParameter( |
| | | event, |
| | | EventParamName(kEventParamDirectObject), |
| | | EventParamType(typeEventHotKeyID), |
| | | nil, |
| | | MemoryLayout<EventHotKeyID>.size, |
| | | nil, |
| | | &hotkeyID |
| | | ) |
| | | guard status == noErr else { return noErr } |
| | | |
| | | let delegate = Unmanaged<AppDelegate> |
| | | .fromOpaque(userData) |
| | | .takeUnretainedValue() |
| | | DispatchQueue.main.async { |
| | | delegate.toggleOverlay() |
| | | delegate.handleHotkeyEvent(id: hotkeyID.id) |
| | | } |
| | | return noErr |
| | | }, |
| | |
| | | selfPtr, |
| | | nil |
| | | ) |
| | | } |
| | | |
| | | private func handleHotkeyEvent(id: UInt32) { |
| | | if id == LauncherHotkeyKind.quickSearch.eventID { |
| | | showQuickSearchFromGlobalHotkey() |
| | | } else { |
| | | performToggleOverlay(preferredScreen: nil) |
| | | } |
| | | } |
| | | |
| | | private func showQuickSearchFromGlobalHotkey() { |
| | | if overlayWindow?.isVisible == true { |
| | | refreshLauncherChromeState( |
| | | activate: !overlayAvoidsSpaceSwitch, |
| | | avoidSpaceSwitch: overlayAvoidsSpaceSwitch |
| | | ) |
| | | requestQuickSearch(source: QuickSearchOpenSource.globalVisible) |
| | | return |
| | | } |
| | | showOverlay(initialQuickSearchSource: QuickSearchOpenSource.globalHidden) |
| | | } |
| | | |
| | | private func hotkeyRef(for kind: LauncherHotkeyKind) -> EventHotKeyRef? { |
| | | switch kind { |
| | | case .main: return mainHotkeyRef |
| | | case .quickSearch: return quickSearchHotkeyRef |
| | | } |
| | | } |
| | | |
| | | private func setHotkeyRef(_ ref: EventHotKeyRef?, for kind: LauncherHotkeyKind) { |
| | | switch kind { |
| | | case .main: mainHotkeyRef = ref |
| | | case .quickSearch: quickSearchHotkeyRef = ref |
| | | } |
| | | } |
| | | |
| | | private func unregisterHotkey(for kind: LauncherHotkeyKind) { |
| | | if let ref = hotkeyRef(for: kind) { |
| | | UnregisterEventHotKey(ref) |
| | | setHotkeyRef(nil, for: kind) |
| | | } |
| | | } |
| | | |
| | | // MARK: - Preferences |
| | |
| | | !self.isInEditMode |
| | | else { return } |
| | | |
| | | if self.isSettingsOwnedPanel(keyWindow) { |
| | | return |
| | | } |
| | | |
| | | if self.isMenuTrackingWindow(keyWindow) { |
| | | return |
| | | } |
| | | |
| | | if self.isAppOwnedDocumentWindow(keyWindow) { |
| | | self.prepareSettingsWindow(keyWindow) |
| | | return |
| | | } |
| | | |
| | | if NSApp.windows.contains(keyWindow) { |
| | | return |
| | | } |
| | | |
| | | // Settings/Preferences window -> float it above overlay for real-time preview. |
| | | if self.isSettingsWindowCandidate(keyWindow) { |
| | | self.prepareSettingsWindow(keyWindow) |
| | |
| | | |
| | | /// Settings must always appear centered over the current overlay view and float above it. |
| | | private func prepareSettingsWindow(_ window: NSWindow) { |
| | | dismissQuickSearchIfNeeded() |
| | | let settingsSize = NSSize(width: 880, height: 460) |
| | | window.identifier = NSUserInterfaceItemIdentifier("TagLauncherPreferencesWindow") |
| | | window.minSize = settingsSize |
| | |
| | | |
| | | var behavior = window.collectionBehavior |
| | | behavior.remove(.canJoinAllSpaces) |
| | | behavior.formUnion([.fullScreenAuxiliary, .moveToActiveSpace]) |
| | | if overlayAvoidsSpaceSwitch { |
| | | behavior.remove(.moveToActiveSpace) |
| | | behavior.formUnion([.fullScreenAuxiliary, .stationary, .transient, .ignoresCycle]) |
| | | } else { |
| | | behavior.formUnion([.fullScreenAuxiliary, .moveToActiveSpace]) |
| | | } |
| | | window.collectionBehavior = behavior |
| | | window.makeKeyAndOrderFront(nil) |
| | | window.orderFrontRegardless() |
| | | settingsWindow = window |
| | | refreshLauncherChromeState( |
| | | activate: !overlayAvoidsSpaceSwitch, |
| | | avoidSpaceSwitch: overlayAvoidsSpaceSwitch |
| | | ) |
| | | } |
| | | |
| | | private func attachSettingsWindow(_ window: NSWindow, to overlayWindow: NSWindow) { |
| | |
| | | private func isSettingsWindowCandidate(_ window: NSWindow) -> Bool { |
| | | if window == settingsWindow { return true } |
| | | if window.identifier?.rawValue == "TagLauncherPreferencesWindow" { return true } |
| | | if isAppOwnedDocumentWindow(window) { return true } |
| | | guard NSApp.windows.contains(window), |
| | | window != overlayWindow, |
| | | window.isVisible, |
| | | !(window is NSPanel) |
| | | else { return false } |
| | | return true |
| | | return settingsWindowTitleCandidates().contains(normalizedWindowTitle(window.title)) |
| | | } |
| | | |
| | | private func isAppOwnedDocumentWindow(_ window: NSWindow) -> Bool { |
| | | NSApp.windows.contains(window) |
| | | && window != overlayWindow |
| | | && window.isVisible |
| | | && !(window is NSPanel) |
| | | && !isMenuTrackingWindow(window) |
| | | && window.styleMask.contains(.titled) |
| | | } |
| | | |
| | | private func isMenuTrackingWindow(_ window: NSWindow) -> Bool { |
| | | let className = NSStringFromClass(type(of: window)) |
| | | return className.localizedCaseInsensitiveContains("Menu") |
| | | || className.localizedCaseInsensitiveContains("Popup") |
| | | } |
| | | |
| | | private func settingsWindowTitleCandidates() -> Set<String> { |
| | | let keys = [ |
| | | "menu.preferences", |
| | | "settings.language", |
| | | "settings.general", |
| | | "quickSearch.hotkeys", |
| | | "settings.tags", |
| | | "settings.data", |
| | | "settings.about" |
| | | ] |
| | | return Set(keys.map { normalizedWindowTitle(tr($0)) }) |
| | | } |
| | | |
| | | private func normalizedWindowTitle(_ title: String) -> String { |
| | | title |
| | | .replacingOccurrences(of: "…", with: "") |
| | | .trimmingCharacters(in: .whitespacesAndNewlines) |
| | | } |
| | | |
| | | private func isSettingsOwnedPanel(_ window: NSWindow) -> Bool { |
| | | guard window is NSPanel else { return false } |
| | | if window is NSSavePanel { return true } |
| | | guard let settingsWindow else { return false } |
| | | return window.sheetParent == settingsWindow |
| | | || settingsWindow.attachedSheet == window |
| | | || window.parent == settingsWindow |
| | | } |
| | | |
| | | private func center(_ window: NSWindow, over rect: NSRect) { |
| | |
| | | } |
| | | |
| | | private func screenUnderMouse() -> NSScreen? { |
| | | let mousePoint = NSEvent.mouseLocation |
| | | return NSScreen.screens.first(where: { |
| | | NSMouseInRect(mousePoint, $0.frame, false) |
| | | }) ?? NSScreen.main ?? NSScreen.screens.first |
| | | overlayController.screenUnderMouse() |
| | | } |
| | | |
| | | /// Clean up settingsWindow reference when the Settings window closes. |
| | |
| | | let closingWindow = notification.object as? NSWindow, |
| | | closingWindow == self.settingsWindow |
| | | else { return } |
| | | let shouldRefocusOverlay = self.isOverlayVisible |
| | | let preferredScreen = self.overlayWindow?.screen |
| | | self.detachSettingsWindow(closingWindow) |
| | | self.settingsWindow = nil |
| | | self.refreshLauncherChromeState( |
| | | activate: shouldRefocusOverlay && !self.overlayAvoidsSpaceSwitch, |
| | | avoidSpaceSwitch: self.overlayAvoidsSpaceSwitch |
| | | ) |
| | | guard shouldRefocusOverlay else { return } |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.12) { [weak self] in |
| | | self?.showOrFocusOverlay(preferredScreen: preferredScreen) |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | /// Lower the overlay while editing app notes so IME candidate windows are not hidden behind it. |
| | | /// Keep text-input overlays at the launcher level so Quick Search stays visible in fullscreen Spaces. |
| | | private func observeAppNoteEditing() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherAppNoteEditingChanged, |
| | |
| | | ) { [weak self] notification in |
| | | guard let self else { return } |
| | | self.isEditingAppNote = (notification.userInfo?["active"] as? Bool) ?? false |
| | | if self.isEditingAppNote { |
| | | self.promoteOverlayToForegroundInput() |
| | | } |
| | | self.updateOverlayLevelForTextInput() |
| | | } |
| | | } |
| | | |
| | | private func promoteOverlayToForegroundInput() { |
| | | if overlayAvoidsSpaceSwitch { |
| | | refreshLauncherChromeState(activate: false, avoidSpaceSwitch: true) |
| | | guard let overlayWindow else { return } |
| | | overlayWindow.makeKeyAndOrderFront(nil) |
| | | overlayWindow.orderFrontRegardless() |
| | | return |
| | | } |
| | | beginLauncherForegroundOwnership() |
| | | guard let overlayWindow else { return } |
| | | overlayWindow.makeKeyAndOrderFront(nil) |
| | | overlayWindow.orderFrontRegardless() |
| | | } |
| | | |
| | | private func observeQuickSearch() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherQuickSearchVisibilityChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | guard let self else { return } |
| | | self.isQuickSearchOpen = (notification.userInfo?["active"] as? Bool) ?? false |
| | | if self.isQuickSearchOpen { |
| | | self.promoteOverlayToForegroundInput() |
| | | } |
| | | self.updateOverlayLevelForTextInput() |
| | | if self.isQuickSearchOpen { |
| | | self.installQuickSearchExternalMouseMonitor() |
| | | } else { |
| | | self.removeQuickSearchExternalMouseMonitor() |
| | | } |
| | | } |
| | | |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherModalInteractionChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | self?.isModalInteractionActive = (notification.userInfo?["active"] as? Bool) ?? false |
| | | } |
| | | |
| | | NotificationCenter.default.addObserver( |
| | | forName: NSApplication.didResignActiveNotification, |
| | | object: NSApp, |
| | | queue: .main |
| | | ) { [weak self] _ in |
| | | self?.handleApplicationDidResignActive() |
| | | } |
| | | } |
| | | |
| | | private func installQuickSearchExternalMouseMonitor() { |
| | | installQuickSearchLocalMouseMonitor() |
| | | guard quickSearchExternalMouseMonitor == nil else { return } |
| | | quickSearchExternalMouseMonitor = NSEvent.addGlobalMonitorForEvents( |
| | | matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown] |
| | | ) { [weak self] _ in |
| | | DispatchQueue.main.async { |
| | | guard self?.isQuickSearchOpen == true else { return } |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | } |
| | | } |
| | | } |
| | | |
| | | private func installQuickSearchLocalMouseMonitor() { |
| | | guard quickSearchLocalMouseMonitor == nil else { return } |
| | | quickSearchLocalMouseMonitor = NSEvent.addLocalMonitorForEvents( |
| | | matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown] |
| | | ) { [weak self] event in |
| | | guard let self, self.isQuickSearchOpen else { return event } |
| | | if event.window === self.overlayWindow { |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | return nil |
| | | } |
| | | return event |
| | | } |
| | | } |
| | | |
| | | private func removeQuickSearchExternalMouseMonitor() { |
| | | if let quickSearchLocalMouseMonitor { |
| | | NSEvent.removeMonitor(quickSearchLocalMouseMonitor) |
| | | self.quickSearchLocalMouseMonitor = nil |
| | | } |
| | | if let quickSearchExternalMouseMonitor { |
| | | NSEvent.removeMonitor(quickSearchExternalMouseMonitor) |
| | | self.quickSearchExternalMouseMonitor = nil |
| | | } |
| | | } |
| | | |
| | | private func updateOverlayLevelForTextInput() { |
| | | guard let overlayWindow else { return } |
| | | overlayWindow.level = isEditingAppNote ? Self.overlayTextInputLevel : Self.overlayDefaultLevel |
| | | overlayWindow.level = currentOverlayLevel |
| | | if let settingsWindow, settingsWindow.parent == overlayWindow { |
| | | settingsWindow.level = overlayWindow.level |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | @objc private func openPreferences() { |
| | | private func observeExternalActivationRequests() { |
| | | DistributedNotificationCenter.default().addObserver( |
| | | self, |
| | | selector: #selector(handleExternalActivationRequest(_:)), |
| | | name: Self.externalActivationNotification, |
| | | object: Self.externalActivationObject |
| | | ) |
| | | } |
| | | |
| | | @objc private func handleExternalActivationRequest(_ notification: Notification) { |
| | | let shouldShowOverlay = notification.userInfo?["showOverlay"] as? Bool ?? true |
| | | guard shouldShowOverlay else { return } |
| | | showOrFocusOverlay() |
| | | } |
| | | |
| | | @objc private func openPreferences(_ sender: Any? = nil) { |
| | | dismissQuickSearchIfNeeded() |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | if overlayAvoidsSpaceSwitch { |
| | | refreshLauncherChromeState(activate: false, avoidSpaceSwitch: true) |
| | | } else { |
| | | beginLauncherForegroundOwnership() |
| | | } |
| | | // Don't hide overlay — keep it visible for real-time setting preview. |
| | | if let overlayWindow, overlayWindow.isVisible { |
| | | overlayWindow.makeKeyAndOrderFront(nil) |
| | | overlayWindow.orderFrontRegardless() |
| | | } |
| | | NSApp.activate(ignoringOtherApps: true) |
| | | |
| | | if let settingsWindow { |
| | | prepareSettingsWindow(settingsWindow) |
| | |
| | | prepareSettingsWindow(window) |
| | | } |
| | | |
| | | private func dismissQuickSearchIfNeeded() { |
| | | guard isQuickSearchOpen else { return } |
| | | isQuickSearchOpen = false |
| | | removeQuickSearchExternalMouseMonitor() |
| | | updateOverlayLevelForTextInput() |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | } |
| | | |
| | | @objc private func switchLanguage(_ sender: NSMenuItem) { |
| | | guard let code = sender.representedObject as? String else { return } |
| | | L10n.switchTo(code) |
| | |
| | | |
| | | final class DismissibleHostingView<Content: View>: NSHostingView<Content> { |
| | | private let onBackdropTap: () -> Void |
| | | private var modalInteractionSuppressesBackdropDismiss = false |
| | | private var quickSearchSuppressesBackdropDismiss = false |
| | | private var modalInteractionObserver: NSObjectProtocol? |
| | | private var quickSearchVisibilityObserver: NSObjectProtocol? |
| | | |
| | | private var suppressBackdropDismiss: Bool { |
| | | modalInteractionSuppressesBackdropDismiss || quickSearchSuppressesBackdropDismiss |
| | | } |
| | | |
| | | @MainActor required init(rootView: Content) { |
| | | self.onBackdropTap = {} |
| | | super.init(rootView: rootView) |
| | | installWindowServerAnchorLayer() |
| | | observeBackdropDismissSuppressionChanges() |
| | | } |
| | | |
| | | init(rootView: Content, onBackdropTap: @escaping () -> Void) { |
| | | self.onBackdropTap = onBackdropTap |
| | | super.init(rootView: rootView) |
| | | installWindowServerAnchorLayer() |
| | | observeBackdropDismissSuppressionChanges() |
| | | } |
| | | |
| | | deinit { |
| | | if let modalInteractionObserver { |
| | | NotificationCenter.default.removeObserver(modalInteractionObserver) |
| | | } |
| | | if let quickSearchVisibilityObserver { |
| | | NotificationCenter.default.removeObserver(quickSearchVisibilityObserver) |
| | | } |
| | | } |
| | | |
| | | @available(*, unavailable) |
| | | required init?(coder: NSCoder) { fatalError() } |
| | | |
| | | private func installWindowServerAnchorLayer() { |
| | | wantsLayer = true |
| | | // A near-transparent backing pixel makes the WindowServer publish the panel immediately. |
| | | layer?.backgroundColor = NSColor.black.withAlphaComponent(0.001).cgColor |
| | | } |
| | | |
| | | override func mouseDown(with event: NSEvent) { |
| | | let location = convert(event.locationInWindow, from: nil) |
| | |
| | | return |
| | | } |
| | | if hit == self { |
| | | if quickSearchSuppressesBackdropDismiss { |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | return |
| | | } |
| | | if suppressBackdropDismiss { |
| | | super.mouseDown(with: event) |
| | | return |
| | | } |
| | | onBackdropTap() |
| | | return |
| | | } |
| | |
| | | super.mouseDown(with: event) |
| | | } |
| | | |
| | | private func observeBackdropDismissSuppressionChanges() { |
| | | modalInteractionObserver = NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherModalInteractionChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | self?.modalInteractionSuppressesBackdropDismiss = (notification.userInfo?["active"] as? Bool) ?? false |
| | | } |
| | | |
| | | quickSearchVisibilityObserver = NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherQuickSearchVisibilityChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | self?.quickSearchSuppressesBackdropDismiss = (notification.userInfo?["active"] as? Bool) ?? false |
| | | } |
| | | } |
| | | |
| | | private func findTextFieldContainer(in view: NSView) -> TextFieldContainer? { |
| | | if let container = view as? TextFieldContainer { return container } |
| | | for sub in view.subviews { |