#!/usr/bin/python

import sys
import pyatspi

def findAppByName(name):
    desktop = pyatspi.Registry.getDesktop(0)
    for app in desktop:
        if app and app.name == name:
            return app

    return None   

def findByRole(root, role):
    return pyatspi.findAllDescendants(root, lambda x: x and x.getRole() == role)

def getAllRangeExtents(obj):
    try:
        text = obj.queryText()
    except NotImplementedError:
        print("%s does not implement the accessible text interface" % obj)

        try:
            obj.getRole()
        except RuntimeError:
            print("Exiting due to dead accessible")
            sys.exit()

    print("Getting range extents for: %s (text: %s, char count: %i)" % (obj, text.getText(0, -1), text.characterCount))
    for x in range(0, text.characterCount):
        try:
            extents = text.getRangeExtents(x, text.characterCount, pyatspi.DESKTOP_COORDS)
        except RuntimeError:
            print("    Extents for offset %i to %i: Exiting due to RuntimeError." % (x, text.characterCount))
            return

        print("    Extents for offset %i to %i %s" % (x, text.characterCount, extents))

def runTest(appname):
    app = findAppByName(appname)
    if not app:
        print("Accessible application '%s' not found" % appname)
        return

    cells = findByRole(app, pyatspi.ROLE_TABLE_CELL)
    for cell in cells:
        getAllRangeExtents(cell)

if __name__ == "__main__":
    runTest("gtk3-demo")
