-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbtail
executable file
·80 lines (59 loc) · 1.68 KB
/
pbtail
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
#!/usr/bin/swift
import Cocoa
func echo(_ string: String, raw: Bool) {
let terminator = raw || string.hasSuffix("\n") ? "" : "\n"
print(string, terminator: terminator)
fflush(stdout)
}
func watchPasteboard(options: Options) {
let pasteboard = NSPasteboard.general
var lastChangeCount = pasteboard.changeCount
if options.printInitialValue {
echo(pasteboard.string(forType: .string) ?? "", raw: options.raw)
}
Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in
if pasteboard.changeCount == lastChangeCount {
return
}
lastChangeCount = pasteboard.changeCount
if let string = pasteboard.string(forType: .string) {
echo(string, raw: options.raw)
}
}
}
func onSIGINT(handler: @escaping () -> Void) {
let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .userInteractive)
let source = DispatchSource.makeSignalSource(signal: SIGINT, queue: queue)
source.setEventHandler(handler: handler)
signal(SIGINT, SIG_IGN)
source.activate()
group.enter()
group.wait()
}
struct Options {
let printInitialValue: Bool
let raw: Bool
init() {
self.printInitialValue = CommandLine.arguments.contains { argument in
argument == "-i" || argument == "--print-initial-value"
}
self.raw = CommandLine.arguments.contains { argument in
argument == "-r" || argument == "--raw"
}
}
}
func main() {
let options = Options()
var shouldKeepRunning = true
DispatchQueue.global(qos: .background).async {
onSIGINT {
shouldKeepRunning = false
}
}
watchPasteboard(options: options)
while shouldKeepRunning {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.05))
}
}
main()