| | |
| | | |
| | | @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) { } |
| | | } |
| | | } |
| | | } |
| | |
| | | private static let statusItemButtonIdentifier = NSUserInterfaceItemIdentifier("TagLauncherStatusItemButton") |
| | | private static let statusItemAccessibilityLabel = AppIdentity.displayName |
| | | private static let showAppListMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherShowAppListMenuItem") |
| | | 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 lastShowDockIcon: Bool? |
| | | private var statusMenuScreenForNextOverlay: NSScreen? |
| | | private var overlayGeneration = 0 |
| | | private var overlayAvoidsSpaceSwitch = false |
| | | private var suppressReopenUntil = Date.distantPast |
| | | |
| | | private struct OverlayPlacementContext { |
| | | let screen: NSScreen |
| | | let frame: NSRect |
| | | } |
| | | |
| | | private struct ForeignWindowFrame { |
| | | let owner: String |
| | | let frame: NSRect |
| | | } |
| | | |
| | |
| | | |
| | | private var requiresForegroundOwnership: Bool { |
| | | isOverlayVisible || isSettingsVisible |
| | | } |
| | | |
| | | private var shouldStageOverlayAsAccessory: Bool { |
| | | !isSettingsVisible && !UserDefaults.standard.bool(forKey: Self.showDockIconKey) |
| | | } |
| | | |
| | | private var currentOverlayLevel: NSWindow.Level { |
| | |
| | | observeAppNoteEditing() |
| | | observeQuickSearch() |
| | | observePreferencesRequests() |
| | | observeExternalActivationRequests() |
| | | observeApplicationMenuChanges() |
| | | observeChromeSettings() |
| | | observeLanguageChanges() |
| | |
| | | /// Dock icon click → show overlay (same as menubar "Show TagLauncher") |
| | | func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { |
| | | guard Date() >= suppressReopenUntil else { return false } |
| | | showOverlay() |
| | | showOrFocusOverlay() |
| | | return false // Suppress default "unhide all windows" behavior |
| | | } |
| | | |
| | |
| | | TagDatabase.flushPendingCategorySchemeBackupBatch() |
| | | removeOverlayKeyMonitor() |
| | | removeQuickSearchExternalMouseMonitor() |
| | | DistributedNotificationCenter.default().removeObserver( |
| | | self, |
| | | name: Self.externalActivationNotification, |
| | | object: Self.externalActivationObject |
| | | ) |
| | | } |
| | | |
| | | /// Ensure defaultGroupName is always the language-neutral key "Other". |
| | |
| | | } |
| | | } |
| | | |
| | | private func refreshLauncherChromeState(activate: Bool = false) { |
| | | private func refreshLauncherChromeState(activate: Bool = false, avoidSpaceSwitch: Bool = false) { |
| | | let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey) |
| | | lastShowDockIcon = showDock |
| | | |
| | | let desiredPolicy: NSApplication.ActivationPolicy = requiresForegroundOwnership |
| | | let shouldStayAccessoryForCurrentFullscreenSpace = isOverlayVisible |
| | | && (avoidSpaceSwitch || overlayAvoidsSpaceSwitch) |
| | | let desiredPolicy: NSApplication.ActivationPolicy = shouldStayAccessoryForCurrentFullscreenSpace |
| | | ? .accessory |
| | | : (requiresForegroundOwnership |
| | | ? .regular |
| | | : (showDock ? .regular : .accessory) |
| | | : (showDock ? .regular : .accessory)) |
| | | if NSApp.activationPolicy() != desiredPolicy { |
| | | NSApp.setActivationPolicy(desiredPolicy) |
| | | } |
| | |
| | | NSApp.presentationOptions = desiredPresentation |
| | | } |
| | | |
| | | if activate && requiresForegroundOwnership { |
| | | if activate && requiresForegroundOwnership && !shouldStayAccessoryForCurrentFullscreenSpace { |
| | | let keyWindow = isSettingsVisible ? settingsWindow : (isOverlayVisible ? overlayWindow : nil) |
| | | claimLauncherForeground( |
| | | keyWindow: keyWindow, |
| | |
| | | } |
| | | |
| | | private func handleApplicationDidResignActive() { |
| | | guard !isOverlayVisible else { |
| | | return |
| | | } |
| | | |
| | | if isQuickSearchOpen { |
| | | NotificationCenter.default.post(name: .tagLauncherQuickSearchDismissRequested, object: nil) |
| | | } |
| | | |
| | | guard !isOverlayVisible else { |
| | | return |
| | | } |
| | | if !requiresForegroundOwnership { |
| | | refreshLauncherChromeState() |
| | | } |
| | |
| | | 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() |
| | | } |
| | | } |
| | |
| | | } |
| | | |
| | | self.configureApplicationMenu() |
| | | self.configureHelpMenu() |
| | | if retries > 0 && self.applicationMenuNeedsCleanup() { |
| | | self.configureApplicationMenuWhenAvailable(retries: retries - 1) |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | 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) |
| | |
| | | } |
| | | } |
| | | |
| | | private func showOrFocusOverlay(preferredScreen: NSScreen? = nil) { |
| | | let placement = overlayPlacementContextForNextOverlay(preferredScreen: preferredScreen) |
| | | let shouldAvoidSpaceSwitch = placement.map { hasFullscreenWindowOnScreen($0.screen) } ?? false |
| | | if let overlayWindow, overlayWindow.isVisible { |
| | | overlayAvoidsSpaceSwitch = shouldAvoidSpaceSwitch |
| | | moveOverlayToCurrentPlacement(preferredScreen: preferredScreen) |
| | | overlayWindow.level = currentOverlayLevel |
| | | refreshLauncherChromeState(activate: !shouldAvoidSpaceSwitch, avoidSpaceSwitch: shouldAvoidSpaceSwitch) |
| | | 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, |
| | |
| | | ) { |
| | | guard let placement = overlayPlacementContextForNextOverlay(preferredScreen: preferredScreen) else { return } |
| | | |
| | | if !stagedForAllSpaces && !isSettingsVisible && NSApp.isActive { |
| | | let shouldAvoidSpaceSwitch = hasFullscreenWindowOnScreen(placement.screen) |
| | | let shouldStageAsAccessory = shouldStageOverlayAsAccessory || shouldAvoidSpaceSwitch |
| | | |
| | | 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) |
| | | } |
| | | NSApp.deactivate() |
| | | if NSApp.isActive { |
| | | NSApp.deactivate() |
| | | } |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) { [weak self] in |
| | | self?.showOverlay( |
| | | initialQuickSearchSource: initialQuickSearchSource, |
| | |
| | | existingWindow.orderOut(nil) |
| | | overlayWindow = nil |
| | | } |
| | | overlayAvoidsSpaceSwitch = shouldAvoidSpaceSwitch |
| | | |
| | | let window = makeOverlayWindow( |
| | | on: placement.screen, |
| | |
| | | overlayGeneration &+= 1 |
| | | overlayWindow = window |
| | | installOverlayKeyMonitor() |
| | | if !isSettingsVisible { |
| | | if shouldStageAsAccessory { |
| | | if NSApp.isActive { |
| | | NSApp.deactivate() |
| | | } |
| | |
| | | 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) |
| | | self.refreshLauncherChromeState(activate: !shouldAvoidSpaceSwitch, avoidSpaceSwitch: shouldAvoidSpaceSwitch) |
| | | if window.frame != placementFrame { |
| | | window.setFrame(placementFrame, display: true) |
| | | window.makeKeyAndOrderFront(nil) |
| | |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidShow, object: nil) |
| | | } |
| | | |
| | | if !isSettingsVisible && stagedForAllSpaces { |
| | | if !isSettingsVisible { |
| | | DispatchQueue.main.asyncAfter(deadline: .now() + 0.12, execute: finishForegroundClaim) |
| | | } else { |
| | | finishForegroundClaim() |
| | | } |
| | | } |
| | | |
| | | private func hasFullscreenWindowOnScreen(_ screen: NSScreen) -> Bool { |
| | | let screenFrame = screen.frame |
| | | let windowFrames = foreignLayerZeroWindows(on: screenFrame) |
| | | |
| | | if windowFrames.contains(where: { isSingleFullscreenWindow($0.frame, on: screenFrame) }) { |
| | | return true |
| | | } |
| | | |
| | | return hasSplitViewFullscreenWindows(windowFrames, on: screenFrame) |
| | | } |
| | | |
| | | private func foreignLayerZeroWindows(on screenFrame: NSRect) -> [ForeignWindowFrame] { |
| | | let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? [] |
| | | return windows.compactMap { info in |
| | | guard let owner = info[kCGWindowOwnerName as String] as? String, |
| | | owner != AppIdentity.displayName, |
| | | owner != "Window Server", |
| | | owner != "Dock", |
| | | owner != "loginwindow", |
| | | let layer = info[kCGWindowLayer as String] as? Int, |
| | | layer == 0, |
| | | let bounds = info[kCGWindowBounds as String] as? NSDictionary |
| | | else { return nil } |
| | | |
| | | let frame = NSRect( |
| | | x: cgWindowDimension(bounds, "X"), |
| | | y: cgWindowDimension(bounds, "Y"), |
| | | width: cgWindowDimension(bounds, "Width"), |
| | | height: cgWindowDimension(bounds, "Height") |
| | | ) |
| | | guard frame.intersects(screenFrame) else { return nil } |
| | | return ForeignWindowFrame(owner: owner, frame: frame) |
| | | } |
| | | } |
| | | |
| | | private func isSingleFullscreenWindow(_ windowFrame: NSRect, on screenFrame: NSRect) -> Bool { |
| | | let widthMatches = abs(windowFrame.width - screenFrame.width) <= 12 |
| | | let heightMatches = windowFrame.height >= screenFrame.height * 0.88 |
| | | let horizontallyAligned = abs(windowFrame.midX - screenFrame.midX) <= 12 |
| | | let verticallyAligned = abs(windowFrame.maxY - screenFrame.maxY) <= 32 |
| | | return widthMatches && heightMatches && horizontallyAligned && verticallyAligned |
| | | } |
| | | |
| | | private func hasSplitViewFullscreenWindows(_ windows: [ForeignWindowFrame], on screenFrame: NSRect) -> Bool { |
| | | let clippedWindows = windows.map { |
| | | ForeignWindowFrame(owner: $0.owner, frame: $0.frame.intersection(screenFrame)) |
| | | } |
| | | let tallWindows = clippedWindows |
| | | .filter { window in |
| | | let frame = window.frame |
| | | return frame.height >= screenFrame.height * 0.86 |
| | | && frame.width >= screenFrame.width * 0.20 |
| | | && frame.width <= screenFrame.width * 0.86 |
| | | && abs(frame.maxY - screenFrame.maxY) <= 32 |
| | | } |
| | | .sorted { $0.frame.minX < $1.frame.minX } |
| | | |
| | | guard tallWindows.count >= 2 else { return false } |
| | | |
| | | for startIndex in tallWindows.indices { |
| | | var union = tallWindows[startIndex].frame |
| | | var lastMaxX = union.maxX |
| | | |
| | | for window in tallWindows.dropFirst(startIndex + 1) { |
| | | let gap = window.frame.minX - lastMaxX |
| | | if gap < -32 || gap > 48 { |
| | | break |
| | | } |
| | | union = union.union(window.frame) |
| | | lastMaxX = max(lastMaxX, window.frame.maxX) |
| | | |
| | | let touchesLeft = abs(union.minX - screenFrame.minX) <= 32 |
| | | let touchesRight = abs(union.maxX - screenFrame.maxX) <= 32 |
| | | let coversWidth = union.width >= screenFrame.width * 0.92 |
| | | let coversHeight = union.height >= screenFrame.height * 0.86 |
| | | if touchesLeft && touchesRight && coversWidth && coversHeight { |
| | | return true |
| | | } |
| | | } |
| | | } |
| | | |
| | | return false |
| | | } |
| | | |
| | | private func cgWindowDimension(_ bounds: NSDictionary, _ key: String) -> CGFloat { |
| | | if let value = bounds[key] as? CGFloat { |
| | | return value |
| | | } |
| | | if let value = bounds[key] as? NSNumber { |
| | | return CGFloat(truncating: value) |
| | | } |
| | | return 0 |
| | | } |
| | | |
| | | private func installOverlayKeyMonitor() { |
| | |
| | | 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 |
| | | } |
| | |
| | | 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 |
| | | } |
| | |
| | | !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 |
| | | // This combination keeps the overlay on the pointer display, including fullscreen Spaces. |
| | | // Keep the overlay publishable above fullscreen Spaces without asking |
| | | // AppKit to migrate an all-spaces window between Spaces. |
| | | panel.collectionBehavior = [ |
| | | .canJoinAllSpaces, |
| | | .fullScreenAuxiliary, |
| | |
| | | overlayWindow?.orderOut(nil) |
| | | removeOverlayKeyMonitor() |
| | | removeQuickSearchExternalMouseMonitor() |
| | | overlayAvoidsSpaceSwitch = false |
| | | refreshLauncherChromeState() |
| | | NotificationCenter.default.post(name: .tagLauncherOverlayDidHide, object: nil) |
| | | if discardWindow { |
| | |
| | | |
| | | private func showQuickSearchFromGlobalHotkey() { |
| | | if overlayWindow?.isVisible == true { |
| | | guard !isSettingsVisible else { return } |
| | | refreshLauncherChromeState(activate: true) |
| | | NotificationCenter.default.post( |
| | | name: .tagLauncherQuickSearchRequested, |
| | | object: nil, |
| | | userInfo: ["source": QuickSearchOpenSource.globalVisible] |
| | | refreshLauncherChromeState( |
| | | activate: !overlayAvoidsSpaceSwitch, |
| | | avoidSpaceSwitch: overlayAvoidsSpaceSwitch |
| | | ) |
| | | requestQuickSearch(source: QuickSearchOpenSource.globalVisible) |
| | | return |
| | | } |
| | | showOverlay(initialQuickSearchSource: QuickSearchOpenSource.globalHidden) |
| | |
| | | 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) |
| | |
| | | |
| | | 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: true) |
| | | 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 { |
| | |
| | | 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() |
| | | 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) |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | |
| | | 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) |
| | |
| | | } |
| | | } |
| | | |
| | | 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() |
| | | 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) |