Skip to content

Instantly share code, notes, and snippets.

@mksh
Forked from glyph/onlock.py
Created February 15, 2014 22:20
Show Gist options
  • Save mksh/9025973 to your computer and use it in GitHub Desktop.
Save mksh/9025973 to your computer and use it in GitHub Desktop.
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()
@mksh
Copy link
Author

mksh commented Mar 19, 2014

:3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment