#!/usr/bin/python

import pyatspi
import sys

GROUP_CELL_NAMES = ["Places", "Devices", "Bookmarks", "Network"]

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

    return None

def findAllByRole(root, role):
    if not root:
        return []

    pred = lambda x: x and x.getRole() == role and pyatspi.listInterfaces(x).count('Text')
    return pyatspi.findAllDescendants(root, lambda x: x and x.getRole() == role)

def printFirstLine(obj):
    try:
        text = obj.queryText()
    except NotImplementedError:
        return
    else:
        if not text.characterCount:
            return
    try:
        line = text.getTextAtOffset(0, pyatspi.TEXT_BOUNDARY_LINE_START)
        result = "<%s>" % line[0]
    except:
        result = "(EXCEPTION)"

    print("Name: <%s>\nLine: %s\n" % (obj.name, result))

def main():
    allCells = findAllByRole(findApp("nautilus"), pyatspi.ROLE_TABLE_CELL)
    itemCells = []
    groupCells = []
    for cell in allCells:
        if cell.name in GROUP_CELL_NAMES:
            groupCells.append(cell)
        else:
            itemCells.append(cell)

    for cell in itemCells:
        printFirstLine(cell)

    for cell in groupCells:
        printFirstLine(cell)

    sys.exit(0)

if __name__ == "__main__":
    main()

