-
Notifications
You must be signed in to change notification settings - Fork 4
/
lockscreen.swift
66 lines (54 loc) · 1.87 KB
/
lockscreen.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
import Darwin
import IOKit
import IOKit.usb
import Foundation
func lockScreenImmediate() -> Void {
let libHandle = dlopen("/System/Library/PrivateFrameworks/login.framework/Versions/Current/login", RTLD_LAZY)
let sym = dlsym(libHandle, "SACLockScreenImmediate")
typealias myFunction = @convention(c) () -> Void
let SACLockScreenImmediate = unsafeBitCast(sym, to: myFunction.self)
SACLockScreenImmediate()
}
class Notifier {
let callbackQueue: DispatchQueue = DispatchQueue.global()
func dispatchEvent (iterator: io_iterator_t) {
repeat {
let next = IOIteratorNext(iterator)
guard next != 0 else { break }
self.callbackQueue.async {
lockScreenImmediate()
IOObjectRelease(next)
}
} while (true)
}
}
let notifier = Notifier()
let notifierPtr = Unmanaged.passUnretained(notifier).toOpaque()
var iterator: io_iterator_t = 0
let internalQueue: DispatchQueue = DispatchQueue(label: "IODetector")
let notifyPort: IONotificationPortRef = IONotificationPortCreate(kIOMainPortDefault)
IONotificationPortSetDispatchQueue(notifyPort, internalQueue)
let matchingDict = IOServiceMatching(kIOUSBDeviceClassName) as NSMutableDictionary
matchingDict[kUSBVendorID] = 0x1050
matchingDict[kUSBProductID] = "*"
let cb: IOServiceMatchingCallback = { (userData, iterator) in notifier.dispatchEvent(iterator: iterator) };
let error = IOServiceAddMatchingNotification(notifyPort, kIOTerminatedNotification, matchingDict, cb, notifierPtr, &iterator)
guard error == 0 else {
if iterator != 0 {
IOObjectRelease(iterator)
iterator = 0
}
exit(1)
}
notifier.dispatchEvent(iterator: iterator)
signal(SIGINT) {
s in
if iterator != 0 {
IOObjectRelease(iterator)
iterator = 0
}
exit(1)
}
CFRunLoopRun()
IOObjectRelease(iterator)
iterator = 0