#!/usr/bin/python
import pyatspi

def listener(e):
    # We don't care about what became unselected or unfocused
    if not e.detail1:
        return

    try:
        appName = e.host_application.name
        name = e.source.name
        role = e.source.getRole()
        relations = e.source.getRelationSet()
    except RuntimeError:
        return

    if appName != 'gnome-shell' or role != pyatspi.ROLE_PUSH_BUTTON:
        return

    labels = []
    isLabelledBy = lambda r: r.getRelationType() == pyatspi.RELATION_LABELLED_BY
    for r in filter(isLabelledBy, relations):
        labels.extend([r.getTarget(i) for i in range(r.getNTargets())])

    labelNames = ' '.join([x.name for x in labels])
    print ("Name: <%s> Label count: %s Label(s) name: <%s>" % (name, len(labels), labelNames))

pyatspi.Registry.registerEventListener(listener, 'object:state-changed:selected', 'object:state-changed:focused')
pyatspi.Registry.start()
