| | |
| | | |
| | | @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) { } |
| | | } |
| | | } |
| | | } |
| | |
| | | final class OverlayPanel: NSPanel { |
| | | override var canBecomeKey: Bool { true } |
| | | override var canBecomeMain: Bool { true } |
| | | |
| | | override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect { |
| | | frameRect |
| | | } |
| | | } |
| | | |
| | | 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 overlayDefaultLevel = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.maximumWindow))) |
| | | private static let overlayTextInputLevel = NSWindow.Level.modalPanel |
| | | 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 quickSearchExternalMouseMonitor: Any? |
| | | private var settingsWindow: NSWindow? // Track Settings window to keep it above overlay |
| | | private var mainHotkeyRef: EventHotKeyRef? |
| | | private var quickSearchHotkeyRef: EventHotKeyRef? |
| | | private var hotkeyEventHandlerInstalled = false |
| | | private var isQuickSearchOpen = false |
| | | private var isModalInteractionActive = false |
| | | private var areHotkeysPausedForCapture = 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 overlayGeneration = 0 |
| | | private var suppressReopenUntil = Date.distantPast |
| | | |
| | | private struct OverlayPlacementContext { |
| | | let screen: NSScreen |
| | | let frame: NSRect |
| | | } |
| | | |
| | | 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) |
| | | observeHotkeyStatusChanges() |
| | | registerConfiguredHotkeys() |
| | | observeOtherWindows() |
| | | observeSettingsClose() |
| | |
| | | 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) { |
| | | let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey) |
| | | lastShowDockIcon = showDock |
| | | |
| | | let desiredPolicy: NSApplication.ActivationPolicy = 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 { |
| | | 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 = 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 { |
| | | if let hotkey = LauncherHotkeyStore.hotkey(for: .main) { |
| | | return "\(tr("menu.showAppList")) \(hotkey.displayString)" |
| | | if LauncherHotkeyRegistrationStore.state(for: .main) == .failed { |
| | | return tr("menu.showShortcutUnavailable") |
| | | } |
| | | return tr("menu.showAppList") |
| | | return "\(tr("menu.showAppList")) \(LauncherHotkey.main.displayString)" |
| | | } |
| | | |
| | | private func observeApplicationMenuChanges() { |
| | |
| | | } |
| | | |
| | | self.configureApplicationMenu() |
| | | self.removeHelpMenu() |
| | | 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 removeHelpMenu() { |
| | | guard let mainMenu = NSApp.mainMenu else { return } |
| | | NSApp.helpMenu = nil |
| | | |
| | | for item in mainMenu.items.reversed() { |
| | | let isHelpMenu = item.submenu === NSApp.helpMenu |
| | | || 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) |
| | | } |
| | | } |
| | | } |
| | | |
| | | 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(initialQuickSearchSource: String? = nil) { |
| | | // 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 } |
| | | |
| | | let window: NSWindow |
| | | if let existingWindow = overlayWindow { |
| | | window = existingWindow |
| | | private func performToggleOverlay(preferredScreen: NSScreen?) { |
| | | if overlayWindow?.isVisible == true { |
| | | hideOverlay(force: true) |
| | | } else { |
| | | window = makeOverlayWindow(on: screen, initialQuickSearchSource: initialQuickSearchSource) |
| | | overlayWindow = window |
| | | showOverlay(preferredScreen: preferredScreen) |
| | | } |
| | | } |
| | | |
| | | private func showOrFocusOverlay(preferredScreen: NSScreen? = nil) { |
| | | if let overlayWindow, overlayWindow.isVisible { |
| | | moveOverlayToCurrentPlacement(preferredScreen: preferredScreen) |
| | | overlayWindow.level = currentOverlayLevel |
| | | refreshLauncherChromeState(activate: true) |
| | | overlayWindow.makeKeyAndOrderFront(nil) |
| | | overlayWindow.orderFrontRegardless() |
| | | if let settingsWindow, settingsWindow.isVisible { |
| | | prepareSettingsWindow(settingsWindow) |
| | | } |
| | | return |
| | | } |
| | | showOverlay(preferredScreen: preferredScreen) |
| | | } |
| | | |
| | | private func moveOverlayToCurrentPlacement(preferredScreen: NSScreen?) { |
| | | guard let overlayWindow, |
| | | let placement = overlayPlacementContextForNextOverlay(preferredScreen: preferredScreen), |
| | | overlayWindow.frame != placement.frame |
| | | else { return } |
| | | overlayWindow.setFrame(placement.frame, display: true) |
| | | } |
| | | |
| | | private func showOverlay( |
| | | initialQuickSearchSource: String? = nil, |
| | | preferredScreen: NSScreen? = nil, |
| | | stagedForAllSpaces: Bool = false |
| | | ) { |
| | | guard let placement = overlayPlacementContextForNextOverlay(preferredScreen: preferredScreen) else { return } |
| | | |
| | | let shouldStageAsAccessory = shouldStageOverlayAsAccessory |
| | | |
| | | if !stagedForAllSpaces && shouldStageAsAccessory { |
| | | // Let the all-spaces panel attach to the pointer's display before the app reclaims focus. |
| | | if NSApp.activationPolicy() != .accessory { |
| | | NSApp.setActivationPolicy(.accessory) |
| | | } |
| | | if NSApp.isActive { |
| | | NSApp.deactivate() |
| | | } |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) { [weak self] in |
| | | self?.showOverlay( |
| | | initialQuickSearchSource: initialQuickSearchSource, |
| | | preferredScreen: placement.screen, |
| | | stagedForAllSpaces: true |
| | | ) |
| | | } |
| | | return |
| | | } |
| | | |
| | | window.setFrame(screen.frame, display: true) |
| | | window.level = isEditingAppNote ? Self.overlayTextInputLevel : Self.overlayDefaultLevel |
| | | if overlayWindow?.isVisible == true { |
| | | hideOverlay(force: true) |
| | | } else if let existingWindow = overlayWindow { |
| | | existingWindow.orderOut(nil) |
| | | overlayWindow = nil |
| | | } |
| | | |
| | | let window = makeOverlayWindow( |
| | | on: placement.screen, |
| | | initialQuickSearchSource: initialQuickSearchSource |
| | | ) |
| | | overlayGeneration &+= 1 |
| | | overlayWindow = window |
| | | installOverlayKeyMonitor() |
| | | |
| | | if let initialQuickSearchSource { |
| | | NotificationCenter.default.post( |
| | | name: .tagLauncherQuickSearchRequested, |
| | | object: nil, |
| | | userInfo: ["source": initialQuickSearchSource] |
| | | ) |
| | | if shouldStageAsAccessory { |
| | | if NSApp.isActive { |
| | | NSApp.deactivate() |
| | | } |
| | | if NSApp.activationPolicy() != .accessory { |
| | | NSApp.setActivationPolicy(.accessory) |
| | | } |
| | | } |
| | | |
| | | let targetLevel = overlayLevel(initialQuickSearchSource: initialQuickSearchSource) |
| | | window.setFrame(placement.frame, display: true) |
| | | window.level = targetLevel |
| | | |
| | | window.makeKeyAndOrderFront(nil) |
| | | window.orderFrontRegardless() |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidShow, object: nil) |
| | | |
| | | let placementFrame = placement.frame |
| | | let finishForegroundClaim: () -> Void = { [weak self, weak window] in |
| | | guard let self, let window, self.overlayWindow === window else { return } |
| | | self.refreshLauncherChromeState(activate: true) |
| | | if window.frame != placementFrame { |
| | | window.setFrame(placementFrame, display: true) |
| | | window.makeKeyAndOrderFront(nil) |
| | | window.orderFrontRegardless() |
| | | } |
| | | if let settingsWindow = self.settingsWindow, settingsWindow.isVisible { |
| | | self.prepareSettingsWindow(settingsWindow) |
| | | } |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidShow, object: nil) |
| | | } |
| | | |
| | | if !isSettingsVisible { |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.12, execute: finishForegroundClaim) |
| | | } else { |
| | | finishForegroundClaim() |
| | | } |
| | | } |
| | | |
| | | private func installOverlayKeyMonitor() { |
| | | guard overlayKeyMonitor == nil else { return } |
| | | overlayKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in |
| | | guard let self else { return event } |
| | | guard self.shouldHandleOverlayKeyEvent(event) else { return event } |
| | | if event.keyCode == 53 { // Escape |
| | | if self.isQuickSearchOpen { |
| | | self.isQuickSearchOpen = false |
| | | self.removeQuickSearchExternalMouseMonitor() |
| | | self.updateOverlayLevelForTextInput() |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | return nil |
| | | } |
| | | self.hideOverlay() |
| | | self.hideOverlay(force: true) |
| | | return nil |
| | | } |
| | | if self.shouldOpenQuickSearch(for: event) { |
| | | NotificationCenter.default.post( |
| | | name: .tagLauncherQuickSearchRequested, |
| | | object: nil, |
| | | userInfo: ["source": QuickSearchOpenSource.mainOverlay] |
| | | ) |
| | | self.requestQuickSearch(source: QuickSearchOpenSource.mainOverlay) |
| | | return nil |
| | | } |
| | | return event |
| | | } |
| | | } |
| | | |
| | | 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 { |
| | |
| | | !isModalInteractionActive |
| | | else { return false } |
| | | |
| | | guard let firstResponder = overlayWindow?.firstResponder else { return true } |
| | | if firstResponder is NSText || firstResponder is NSTextField { |
| | | return false |
| | | } |
| | | if let responderView = firstResponder as? NSView, |
| | | viewOrAncestorHandlesSpace(responderView) { |
| | | return false |
| | | } |
| | | return true |
| | | } |
| | | |
| | | private func viewOrAncestorHandlesSpace(_ view: NSView) -> Bool { |
| | | var current: NSView? = view |
| | | while let candidate = current { |
| | | if candidate is NSButton || candidate is NSSegmentedControl || candidate is NSSlider { |
| | | return true |
| | | } |
| | | current = candidate.superview |
| | | } |
| | | return false |
| | | } |
| | | |
| | | private func removeOverlayKeyMonitor() { |
| | |
| | | ) |
| | | panel.isFloatingPanel = true |
| | | panel.hidesOnDeactivate = false |
| | | // Keep the overlay publishable above fullscreen Spaces without asking |
| | | // AppKit to migrate an all-spaces window between Spaces. |
| | | panel.collectionBehavior = [ |
| | | .moveToActiveSpace, |
| | | .canJoinAllSpaces, |
| | | .fullScreenAuxiliary, |
| | | .stationary, |
| | | .transient, |
| | | .ignoresCycle |
| | | ] |
| | | panel.isOpaque = false |
| | | panel.backgroundColor = .clear |
| | | panel.backgroundColor = NSColor.black.withAlphaComponent(0.001) |
| | | panel.hasShadow = false |
| | | panel.titlebarAppearsTransparent = true |
| | | panel.titleVisibility = .hidden |
| | |
| | | return panel |
| | | } |
| | | |
| | | private func hideOverlay(force: Bool = false) { |
| | | private func hideOverlay(force: Bool = false, discardWindow: Bool = false) { |
| | | guard force || !isInEditMode else { return } |
| | | overlayGeneration &+= 1 |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | if let settingsWindow, settingsWindow.parent == overlayWindow { |
| | | detachSettingsWindow(settingsWindow) |
| | | } |
| | | overlayWindow?.orderOut(nil) |
| | | removeOverlayKeyMonitor() |
| | | removeQuickSearchExternalMouseMonitor() |
| | | refreshLauncherChromeState() |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidHide, object: nil) |
| | | if force { |
| | | if discardWindow { |
| | | overlayWindow = nil |
| | | } |
| | | } |
| | |
| | | |
| | | private func registerConfiguredHotkeys() { |
| | | installHotkeyEventHandlerIfNeeded() |
| | | registerStoredHotkey(.main) |
| | | registerStoredHotkey(.quickSearch) |
| | | registerFixedHotkey(.main) |
| | | registerFixedHotkey(.quickSearch) |
| | | } |
| | | |
| | | @discardableResult |
| | | func applyHotkey(_ hotkey: LauncherHotkey?, for kind: LauncherHotkeyKind) -> Bool { |
| | | installHotkeyEventHandlerIfNeeded() |
| | | |
| | | if hotkey == nil { |
| | | unregisterHotkey(for: kind) |
| | | LauncherHotkeyStore.save(nil, for: kind) |
| | | LauncherHotkeyStore.setStatus(.disabled, message: nil, for: kind) |
| | | return true |
| | | } |
| | | |
| | | guard let hotkey else { return false } |
| | | let previousRef = hotkeyRef(for: kind) |
| | | if previousRef != nil, LauncherHotkeyStore.hotkey(for: kind) == hotkey { |
| | | LauncherHotkeyStore.setStatus(.active, message: nil, for: kind) |
| | | return true |
| | | } |
| | | setHotkeyRef(nil, for: kind) |
| | | private func registerFixedHotkey(_ kind: LauncherHotkeyKind) { |
| | | unregisterHotkey(for: kind) |
| | | let hotkey = kind.hotkey |
| | | |
| | | var hotkeyID = EventHotKeyID() |
| | | hotkeyID.signature = OSType(0x41505447) // 'APTG' |
| | |
| | | ) |
| | | |
| | | if status == noErr, let newRef { |
| | | if let previousRef { UnregisterEventHotKey(previousRef) } |
| | | setHotkeyRef(newRef, for: kind) |
| | | LauncherHotkeyStore.save(hotkey, for: kind) |
| | | LauncherHotkeyStore.setStatus(.active, message: nil, for: kind) |
| | | return true |
| | | LauncherHotkeyRegistrationStore.setActive(for: kind) |
| | | } else { |
| | | setHotkeyRef(nil, for: kind) |
| | | LauncherHotkeyRegistrationStore.setFailed(status, for: kind) |
| | | print("[TagLauncher] Fixed hotkey registration failed for \(kind.rawValue): \(status)") |
| | | } |
| | | |
| | | setHotkeyRef(previousRef, for: kind) |
| | | let message = LauncherHotkeyStore.knownConflictMessage(for: hotkey, status: status) |
| | | ?? tr("quickSearch.hotkeyConflict.generic") |
| | | LauncherHotkeyStore.savePending(hotkey, for: kind) |
| | | LauncherHotkeyStore.setStatus(.conflict, message: message, for: kind) |
| | | print("[TagLauncher] Hotkey registration failed for \(kind.rawValue): \(status)") |
| | | return false |
| | | } |
| | | |
| | | func retryHotkeyRegistration(for kind: LauncherHotkeyKind) { |
| | | _ = applyHotkey( |
| | | LauncherHotkeyStore.pendingHotkey(for: kind) ?? LauncherHotkeyStore.hotkey(for: kind), |
| | | for: kind |
| | | ) |
| | | } |
| | | |
| | | private func registerStoredHotkey(_ kind: LauncherHotkeyKind) { |
| | | _ = applyHotkey(LauncherHotkeyStore.hotkey(for: kind), for: kind) |
| | | private func observeHotkeyStatusChanges() { |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherHotkeyRegistrationChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] _ in |
| | | self?.setupMenuBar() |
| | | self?.configureApplicationMenuWhenAvailable(retries: 2) |
| | | } |
| | | } |
| | | |
| | | private func installHotkeyEventHandlerIfNeeded() { |
| | |
| | | if id == LauncherHotkeyKind.quickSearch.eventID { |
| | | showQuickSearchFromGlobalHotkey() |
| | | } else { |
| | | toggleOverlay() |
| | | performToggleOverlay(preferredScreen: nil) |
| | | } |
| | | } |
| | | |
| | | private func showQuickSearchFromGlobalHotkey() { |
| | | guard overlayWindow?.isVisible != true else { return } |
| | | if overlayWindow?.isVisible == true { |
| | | refreshLauncherChromeState(activate: true) |
| | | requestQuickSearch(source: QuickSearchOpenSource.globalVisible) |
| | | return |
| | | } |
| | | showOverlay(initialQuickSearchSource: QuickSearchOpenSource.globalHidden) |
| | | } |
| | | |
| | |
| | | keyWindow != self.overlayWindow, |
| | | !self.isInEditMode |
| | | else { return } |
| | | |
| | | if self.isSettingsOwnedPanel(keyWindow) { |
| | | return |
| | | } |
| | | |
| | | // Settings/Preferences window -> float it above overlay for real-time preview. |
| | | if self.isSettingsWindowCandidate(keyWindow) { |
| | |
| | | window.makeKeyAndOrderFront(nil) |
| | | window.orderFrontRegardless() |
| | | settingsWindow = window |
| | | refreshLauncherChromeState(activate: true) |
| | | } |
| | | |
| | | private func attachSettingsWindow(_ window: NSWindow, to overlayWindow: NSWindow) { |
| | |
| | | window.isVisible, |
| | | !(window is NSPanel) |
| | | else { return false } |
| | | return true |
| | | return settingsWindowTitleCandidates().contains(normalizedWindowTitle(window.title)) |
| | | } |
| | | |
| | | 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? { |
| | | overlayPlacementContextForNextOverlay(preferredScreen: nil)?.screen |
| | | } |
| | | |
| | | private func overlayPlacementContextForNextOverlay(preferredScreen: NSScreen?) -> OverlayPlacementContext? { |
| | | if let screen = preferredScreen { |
| | | return OverlayPlacementContext(screen: screen, frame: screen.frame) |
| | | } |
| | | guard let screen = screenContainingCurrentPointer() ?? NSScreen.main ?? NSScreen.screens.first else { |
| | | return nil |
| | | } |
| | | return OverlayPlacementContext(screen: screen, frame: screen.frame) |
| | | } |
| | | |
| | | private func screenContainingCurrentPointer() -> NSScreen? { |
| | | let mousePoint = NSEvent.mouseLocation |
| | | return NSScreen.screens.first(where: { |
| | | NSMouseInRect(mousePoint, $0.frame, false) |
| | | }) ?? NSScreen.main ?? NSScreen.screens.first |
| | | }) |
| | | } |
| | | |
| | | /// 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) |
| | | 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() { |
| | | beginLauncherForegroundOwnership() |
| | | guard let overlayWindow else { return } |
| | | overlayWindow.makeKeyAndOrderFront(nil) |
| | | overlayWindow.orderFrontRegardless() |
| | | } |
| | | |
| | | private func observeQuickSearch() { |
| | |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | self?.isQuickSearchOpen = (notification.userInfo?["active"] as? Bool) ?? false |
| | | 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( |
| | |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | guard let self else { return } |
| | | let active = (notification.userInfo?["active"] as? Bool) ?? false |
| | | self.isModalInteractionActive = active |
| | | if (notification.userInfo?["source"] as? String) == "hotkeyRecording" { |
| | | self.setHotkeysPausedForCapture(active) |
| | | } |
| | | self?.isModalInteractionActive = (notification.userInfo?["active"] as? Bool) ?? false |
| | | } |
| | | |
| | | NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherHotkeysChanged, |
| | | object: nil, |
| | | forName: NSApplication.didResignActiveNotification, |
| | | object: NSApp, |
| | | queue: .main |
| | | ) { [weak self] _ in |
| | | self?.setupMenuBar() |
| | | self?.configureApplicationMenuWhenAvailable(retries: 2) |
| | | self?.handleApplicationDidResignActive() |
| | | } |
| | | } |
| | | |
| | | private func installQuickSearchExternalMouseMonitor() { |
| | | 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 removeQuickSearchExternalMouseMonitor() { |
| | | 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 |
| | | } |
| | | } |
| | | |
| | | private func setHotkeysPausedForCapture(_ paused: Bool) { |
| | | guard areHotkeysPausedForCapture != paused else { return } |
| | | areHotkeysPausedForCapture = paused |
| | | if paused { |
| | | unregisterHotkey(for: .main) |
| | | unregisterHotkey(for: .quickSearch) |
| | | } else { |
| | | registerConfiguredHotkeys() |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | @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) { |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | 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) |
| | |
| | | |
| | | final class DismissibleHostingView<Content: View>: NSHostingView<Content> { |
| | | private let onBackdropTap: () -> Void |
| | | private var suppressBackdropDismiss = false |
| | | 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) |
| | | observeModalInteractionChanges() |
| | | installWindowServerAnchorLayer() |
| | | observeBackdropDismissSuppressionChanges() |
| | | } |
| | | |
| | | init(rootView: Content, onBackdropTap: @escaping () -> Void) { |
| | | self.onBackdropTap = onBackdropTap |
| | | super.init(rootView: rootView) |
| | | observeModalInteractionChanges() |
| | | 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 |
| | |
| | | super.mouseDown(with: event) |
| | | } |
| | | |
| | | private func observeModalInteractionChanges() { |
| | | private func observeBackdropDismissSuppressionChanges() { |
| | | modalInteractionObserver = NotificationCenter.default.addObserver( |
| | | forName: .tagLauncherModalInteractionChanged, |
| | | object: nil, |
| | | queue: .main |
| | | ) { [weak self] notification in |
| | | self?.suppressBackdropDismiss = (notification.userInfo?["active"] as? Bool) ?? false |
| | | 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 |
| | | } |
| | | } |
| | | |