import AppKit import Foundation /// Brings the terminal that owns a luxe session to the front. enum TerminalFocuser { /// Returns false when nothing could be activated, so the caller can say so instead of doing nothing. @discardableResult static func focus(bundleID: String?) -> Bool { guard let bundleID else { NSLog("LuxeNotifier: event carried no terminal; cannot focus") return false } guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) else { NSLog("LuxeNotifier: no installed app with bundle id \(bundleID)") return false } let running = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).first let activated = running?.activate(options: [.activateAllWindows]) ?? false reopen(url: url, bundleID: bundleID, activated: activated) return true } /// activate() gives an app keyboard focus but does not make it raise a window, which left the /// terminal's window under other apps' windows. Opening an already-running app sends it a /// "reopen" request, which apps normally answer by raising or creating a window. private static func reopen(url: URL, bundleID: String, activated: Bool) { let configuration = NSWorkspace.OpenConfiguration() configuration.activates = true NSWorkspace.shared.openApplication(at: url, configuration: configuration) { _, error in let outcome = error.map { "failed: \($0)" } ?? "ok" StatusFile.set("last-focus", "\(bundleID): activate=\(activated), reopen=\(outcome)") } } }