Skip to content

Commit

Permalink
Bring launched app to the foreground on macOS (partially addresses #38)
Browse files Browse the repository at this point in the history
  • Loading branch information
stackotter committed Jan 14, 2024
1 parent afa005a commit 75b5795
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions Sources/swift-bundler/Bundler/Runner/Runner.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import Foundation

#if canImport(AppKit)
import AppKit
#endif

/// A utility for running apps.
enum Runner {
/// Runs the given app.
Expand Down Expand Up @@ -119,8 +123,39 @@ enum Runner {
process.arguments = arguments
process.addEnvironmentVariables(environmentVariables)

return process.runAndWait().mapError { error in
return .failedToRunExecutable(error)
#if canImport(AppKit)
// Bring the app to the foreground once launched.
let center = NSWorkspace.shared.notificationCenter
center.addObserver(
forName: NSWorkspace.didLaunchApplicationNotification,
object: nil,
queue: OperationQueue.main
) { (notification: Notification) in
guard
let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey]
as? NSRunningApplication,
app.bundleURL == bundle
else {
return
}

app.activate()
}
#endif

do {
try process.run()
} catch {
return .failure(.failedToRunExecutable(.failedToRunProcess(error)))
}

process.waitUntilExit()

let exitStatus = Int(process.terminationStatus)
if exitStatus != 0 {
return .failure(.failedToRunExecutable(.nonZeroExitStatus(exitStatus)))
} else {
return .success()
}
}

Expand Down

0 comments on commit 75b5795

Please sign in to comment.