#!/usr/bin/python

import pyatspi

def displayedText(obj):
    if obj.name:
        return obj.name

    try:
        return obj.queryText().getText(0, -1)
    except:
        if obj.childCount:
            return displayedText(obj[0])

    return "(no name or text)"

def getLabelsFor(obj):
    try:
        relations = obj.getRelationSet()
    except:
        relations = []
    if not relations:
        return

    isLabelledBy = lambda r: r.getRelationType() == pyatspi.RELATION_LABELLED_BY
    labelledByRelation = list(filter(isLabelledBy, relations))
    if not labelledByRelation:
        return

    labels = []
    for r in labelledByRelation:
        targets = [r.getTarget(i) for i in range(r.getNTargets())]
        labels.extend(list(map(displayedText, targets)))

    return labels

def onStateChanged(event):
    if not event.detail1:
        return

    print("%s is labelled by: %s" % (event.source, getLabelsFor(event.source)))    

pyatspi.Registry.registerEventListener(
    onStateChanged, "object:state-changed:selected", "object:state-changed:focused")
pyatspi.Registry.start()
