#!/usr/bin/python3
import pyatspi

def getLabel(obj):
    try:
        relations = obj.getRelationSet()
    except:
        return ""

    for relation in relations:
        if relation.getRelationType() == pyatspi.RELATION_LABELLED_BY:
            return relation.getTarget(0).name

    return ""

def listener(e):
    if not e.detail1:
        return

    try:
        appName = e.host_application.name
    except:
        return
    if appName != "gnome-shell":
        return

    try:
        labelOrName = e.source.name or getLabel(e.source) or "UNNAMED"
        roleName = e.source.getRoleName()
    except:
        pass
    else:
        print(labelOrName, roleName)

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