import pyatspi

foo = []

def genericHandler(event):
    print "event: %s" % event.type
    print "event.host_application:", event.host_application
    print "event.source.getApplication():", event.source.getApplication()
    obj = event.source
    roleList = [pyatspi.ROLE_FILLER,
                pyatspi.ROLE_SPLIT_PANE,
                pyatspi.ROLE_FILLER,
                pyatspi.ROLE_DOCUMENT_FRAME]
    for role in roleList:
        for child in obj:
            if child.getRole() == role:
                if role == pyatspi.ROLE_DOCUMENT_FRAME:
                    return child
                else:
                    obj = child
                    break

    for child in event.source:
        print child.getRole()

def onCaretMoved(event):
    print "caret moved: %s" % event.source.getRoleName()
    print "event.host_application:", event.host_application.getRoleName(), event.host_application
    print "event.source.getApplication():", event.source.getApplication()
    #print "ancestry of event.source:"
    #ancestorList = [event.source]
    #parent = event.source.parent
    #while parent and (parent.parent != parent):
    #    ancestorList.insert(0, parent)
    #    parent = parent.parent

    #indent = ""
    #for ancestor in ancestorList:
    #    print indent + "+-", ancestor
    #    indent += "  "

pyatspi.Registry.registerEventListener(genericHandler,
                                       "window:activate")
pyatspi.Registry.registerEventListener(onCaretMoved,
                                       "object:text-caret-moved")

apps = filter(lambda x: x is not None,
              pyatspi.Registry.getDesktop(0))
for app in apps:
    print app

pyatspi.Registry.start()
