#!/usr/bin/python

import pyatspi
from gi.repository import Gtk

class Tester:

    def __init__(self, roles):
        self.roles = roles

    def start(self):
        pyatspi.Registry.registerKeystrokeListener(
            self.onKeyboardEvent,
            mask=range(255),
            kind=(pyatspi.KEY_PRESSED_EVENT,))
        pyatspi.Registry.registerEventListener(
            self.onFocused, "object:state-changed:focused")
        pyatspi.Registry.start()

    def stop(self):
        pyatspi.Registry.deregisterEventListener(
            self.onFocused, "object:state-changed:focused")
        pyatspi.Registry.stop()
        Gtk.main_quit()

    def onFocused(self, event):
        if not event.detail1:
            return
        if not event.source.getRole() in self.roles:
            return

        print "%s is focused" % event.source

    def onKeyboardEvent(self, event):
        if event.event_string == 'F12':
            self.stop()
            return True

        return False

if __name__ == '__main__':
    print "\n  Press F12 to Exit\n"
    tester = Tester([pyatspi.ROLE_PUSH_BUTTON, pyatspi.ROLE_CHECK_BOX])
    tester.start()
    Gtk.main()
