Skip to content

Instantly share code, notes, and snippets.

@RoryQ
Last active February 15, 2025 04:31
Show Gist options
  • Select an option

  • Save RoryQ/c1f271301ea32ab9905ca9875198d3a5 to your computer and use it in GitHub Desktop.

Select an option

Save RoryQ/c1f271301ea32ab9905ca9875198d3a5 to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
import Cocoa
// Install with swiftc switchfocus.swift -o switchfocus
// Require command line arguments
guard CommandLine.arguments.count > 1 else {
print("\(CommandLine.arguments[0]): Cycle focus between applications")
print("Example Usage: \(CommandLine.arguments[0]) \"Code\" \"GoLand\" \"Xcode\"")
exit(1)
}
// Get apps from command line arguments
let targetApps = Array(CommandLine.arguments.dropFirst())
func findNextActiveApp() {
let workspace = NSWorkspace.shared
let runningApps = workspace.runningApplications
// Filter to only the specified apps that are running
let activeApps = runningApps.filter { app in
guard let name = app.localizedName else { return false }
return targetApps.contains { name.contains($0) }
}
if activeApps.isEmpty {
print("No matching applications from [\(targetApps.joined(separator: ", "))] are running")
return
}
// Get current active app
guard let currentApp = workspace.frontmostApplication else {
print("Could not determine current active application")
return
}
// Find current app's index
let currentIndex = activeApps.firstIndex(where: {
$0.processIdentifier == currentApp.processIdentifier
}) ?? -1
// Get next app to focus
let nextIndex = (currentIndex + 1) % activeApps.count
let nextApp = activeApps[nextIndex]
// Activate next app
let success = nextApp.activate()
if success {
print("Activated: \(nextApp.localizedName ?? "unknown")")
}
}
findNextActiveApp()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment