Created
February 12, 2014 23:37
-
-
Save glyph/8966828 to your computer and use it in GitHub Desktop.
onlock.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import os, sys, pipes | |
import objc | |
from Foundation import NSObject | |
from CoreFoundation import ( | |
CFRunLoopRun, CFRunLoopStop, CFFileDescriptorCreate, | |
CFFileDescriptorCreateRunLoopSource, CFRunLoopAddSource, | |
kCFRunLoopDefaultMode, CFRunLoopGetCurrent, | |
CFFileDescriptorEnableCallBacks, kCFFileDescriptorReadCallBack | |
) | |
from AppKit import NSNotificationCenter, NSDistributedNotificationCenter | |
class Locked(NSObject): | |
@objc.selectorFor(NSNotificationCenter.addObserver_selector_name_object_) | |
def observe_(self, notification): | |
command = ' '.join(map(pipes.quote, sys.argv[1:])) | |
print("Sleep: running ", command) | |
os.system(command) | |
nsdnc = NSDistributedNotificationCenter.defaultCenter() | |
nsdnc.addObserver_selector_name_object_( | |
Locked.alloc().init().retain(), "observe:", "com.apple.screenIsLocked", | |
None, | |
) | |
def handle_signals(): | |
def stop(cffd, cbt, info): | |
CFRunLoopStop(CFRunLoopGetCurrent()) | |
r, w = os.pipe() | |
cffd = CFFileDescriptorCreate(None, r, False, stop, None) | |
CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorReadCallBack) | |
cfrlsrc = CFFileDescriptorCreateRunLoopSource(None, cffd, 0) | |
CFRunLoopAddSource(CFRunLoopGetCurrent(), cfrlsrc, kCFRunLoopDefaultMode) | |
def nop(signum, stackframe): | |
pass | |
import signal | |
signal.set_wakeup_fd(w) | |
signal.signal(signal.SIGINT, nop) | |
signal.signal(signal.SIGTERM, nop) | |
handle_signals() | |
CFRunLoopRun() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really helped me a lot!Thank you!