Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import AppKit
// https://stackoverflow.com/a/48486247
func shell(_ launchPath: String, _ arguments: [String]) -> String {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)!
if output.count > 0 {
// remove newline character.
let lastIndex = output.index(before: output.endIndex)
return String(output[output.startIndex ..< lastIndex])
}
return output
}
func main(pattern: String, stop_on_launch: Bool = false) throws {
let workspace = NSWorkspace.shared
let regex = try NSRegularExpression(pattern: "^\(pattern)$")
let is_matching = { (app: NSRunningApplication) -> Bool in
let x = app.bundleIdentifier ?? "[no name]"
return regex.numberOfMatches(in: x, range: NSRange(x.startIndex..., in: x)) > 0
}
// Set of applications to stop
var pids = Set(
workspace.runningApplications
.filter { is_matching($0) }
.map { $0.processIdentifier }
)
let resume_app = { (pid: pid_t) in
print("kill -CONT \(pid)")
shell("/bin/kill", ["-CONT", "\(pid)"])
pids.insert(pid)
}
let stop_apps = { () in
pids.forEach { print("kill -STOP \($0)") }
pids.forEach { shell("/bin/kill", ["-STOP", "\($0)"]) }
pids.removeAll()
}
let token = workspace.observe(\.frontmostApplication) { workspace, _ in
guard let app = workspace.frontmostApplication else {
return
}
print("Switching to: \(app.bundleIdentifier ?? "") (pid: \(app.processIdentifier))")
if is_matching(app) {
resume_app(app.processIdentifier)
} else if (!pids.isEmpty) {
stop_apps()
}
}
if stop_on_launch {
stop_apps()
}
RunLoop.current.run(
mode: RunLoopMode.defaultRunLoopMode,
before: NSDate.distantFuture
)
}
do {
try main(pattern: CommandLine.arguments[1])
} catch {
print("Invalid regexp pattern")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.