Skip to content

Instantly share code, notes, and snippets.

@hiway
Created December 22, 2012 13:08
Show Gist options
  • Save hiway/4358850 to your computer and use it in GitHub Desktop.
Save hiway/4358850 to your computer and use it in GitHub Desktop.
Logs activity of key presses and mouse left-click, displays an icon in system menubar to depict activity mode. Can be used as boilerplate for sending activity log to server every x minutes.
import time
from Cocoa import *
from Foundation import *
from PyObjCTools import AppHelper
last_timestamp = time.time()
# put two images, 16*16px in a subdirectory called 'resources'
status_images = {
'inactive':'./resources/inactive.png',
'active':'./resources/active.png',
}
start_time = NSDate.date()
class AppDelegate(NSObject):
images = {}
status_bar = None
state = 'inactive'
timeout = 30 # seconds
def applicationDidFinishLaunching_(self, notification):
# Monitor keypresses
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
NSKeyDownMask, activity_handler
)
# Monitor mouse left-clicks
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
NSLeftMouseDownMask, activity_handler
)
status_bar = NSStatusBar.systemStatusBar()
self.status_item = status_bar.statusItemWithLength_(
NSVariableStatusItemLength)
# Load images
for i in status_images.keys():
self.images[i] = NSImage.alloc().initByReferencingFile_(
status_images[i])
self.status_item.setImage_(self.images['inactive'])
self.status_item.setToolTip_('Activity Logger')
# Build menu
self.menu = NSMenu.alloc().init()
menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Quit', 'terminate:', ''
)
self.menu.addItem_(menu_item)
self.status_item.setMenu_(self.menu)
self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(
start_time, 5.0, self, 'tick:', None, True
)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
self.timer.fire()
def tick_(self, notification):
global last_timestamp
if time.time() < (last_timestamp + self.timeout):
self.state = 'active'
else:
self.state = 'inactive'
self.status_item.setImage_(self.images[self.state])
print self.state, time.time(), last_timestamp
def activity_handler(event):
"""Gets called every time there's an event/activity happening.
Sets last_timestamp to the time when an event occurs.
This can be used by a thread that's checking if there was any
activity in the last x minutes."""
global last_timestamp
last_timestamp = time.time()
def main():
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment