Skip to content

Instantly share code, notes, and snippets.

@r0ysue
Forked from glyph/onlock.py
Created October 7, 2017 03:15
Show Gist options
  • Save r0ysue/359c67381fbacb5e4d92a396988f95b5 to your computer and use it in GitHub Desktop.
Save r0ysue/359c67381fbacb5e4d92a396988f95b5 to your computer and use it in GitHub Desktop.
onlock.py
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