-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrun-on-macos-screen-unlock.swift
executable file
·159 lines (131 loc) · 4.63 KB
/
run-on-macos-screen-unlock.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import Foundation
let name = (CommandLine.arguments[0] as NSString).lastPathComponent
let version = "1.0.1"
let build = "2024-08-20-001"
let author = "AJ ONeal <[email protected]>"
let versionMessage = "\(name) \(version) (\(build))"
let copyrightMessage = "Copyright 2024 \(author)"
let helpMessage = """
Runs a user-specified command whenever the screen is unlocked by
listening for the "com.apple.screenIsUnlocked" event, using /usr/bin/command -v
to find the program in the user's PATH (or the explicit path given), and then
runs it with /usr/bin/command, which can run aliases and shell functions also.
USAGE
\(name) [OPTIONS] <command> [--] [command-arguments]
OPTIONS
--version, -V, version
Display the version information and exit.
--help, help
Display this help and exit.
"""
signal(SIGINT) { _ in
printForHuman("received ctrl+c, exiting...")
exit(0)
}
func printForHuman(_ message: String) {
if let data = "\(message)\n".data(using: .utf8) {
FileHandle.standardError.write(data)
}
}
func getCommandPath(_ command: String) -> String? {
let commandv = Process()
commandv.launchPath = "/usr/bin/command"
commandv.arguments = ["-v", command]
let pipe = Pipe()
commandv.standardOutput = pipe
commandv.standardError = FileHandle.standardError
try! commandv.run()
commandv.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let commandPath = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines)
else {
return nil
}
if commandv.terminationStatus != 0, commandPath.isEmpty {
return nil
}
return commandPath
}
class ScreenLockObserver {
var commandPath: String
var commandArgs: ArraySlice<String>
init(_ commandArgs: ArraySlice<String>) {
self.commandPath = commandArgs.first!
self.commandArgs = commandArgs
let dnc = DistributedNotificationCenter.default()
_ = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsLocked"), object: nil, queue: .main) { _ in
NSLog("notification: com.apple.screenIsLocked")
}
NSLog("Waiting for 'com.apple.screenIsUnlocked' to run \(self.commandArgs)")
_ = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsUnlocked"), object: nil, queue: .main) { _ in
NSLog("notification: com.apple.screenIsUnlocked")
self.runOnUnlock()
}
}
private func runOnUnlock() {
let task = Process()
task.launchPath = "/usr/bin/command"
task.arguments = Array(commandArgs)
task.standardOutput = FileHandle.standardOutput
task.standardError = FileHandle.standardError
do {
try task.run()
} catch {
printForHuman("Failed to run \(self.commandPath): \(error.localizedDescription)")
if let nsError = error as NSError? {
printForHuman("Error details: \(nsError)")
}
exit(1)
}
task.waitUntilExit()
}
}
@discardableResult
func removeItem(_ array: inout ArraySlice<String>, _ item: String) -> Bool {
if let index = array.firstIndex(of: item) {
array.remove(at: index)
return true
}
return false
}
func processArgs(_ args: inout ArraySlice<String>) -> ArraySlice<String> {
var childArgs: ArraySlice<String> = []
if let delimiterIndex = args.firstIndex(of: "--") {
let childArgsIndex = delimiterIndex + 1
childArgs = args[childArgsIndex...]
args.removeSubrange(delimiterIndex...)
}
if removeItem(&args, "--help") || removeItem(&args, "help") {
printForHuman(versionMessage)
printForHuman("")
printForHuman(helpMessage)
printForHuman("")
printForHuman(copyrightMessage)
exit(0)
}
if removeItem(&args, "--version") || removeItem(&args, "-V") || removeItem(&args, "version") {
printForHuman(versionMessage)
printForHuman(copyrightMessage)
exit(0)
}
childArgs = args + childArgs
guard let commandName = childArgs.first else {
printForHuman(versionMessage)
printForHuman("")
printForHuman(helpMessage)
printForHuman("")
printForHuman(copyrightMessage)
exit(1)
}
guard let commandPath = getCommandPath(commandName) else {
printForHuman("ERROR:\n \(commandName) not found in PATH")
exit(1)
}
childArgs[childArgs.startIndex] = commandPath
return childArgs
}
var args = CommandLine.arguments[1...]
let commandArgs = processArgs(&args)
_ = ScreenLockObserver(commandArgs)
RunLoop.main.run()