#!/usr/bin/python

import pyatspi, sys
reg = pyatspi.Registry

sampling_size = 100000

def str_acc(acc):
  return '[%s | %s]' % (acc.getRoleName(), acc.name)

def get_button_in_helloworld():
  acc = None
  desktop = reg.getDesktop(0)
  for i in xrange(desktop.childCount):
    try:
      app = desktop.getChildAtIndex(i)
    except:
      continue
    if app is None: continue
    if app.name == 'helloworld':
      # Get the root pane
      acc = app.getChildAtIndex(0).getChildAtIndex(0)
      break
  return acc

def get_related_label():
  acc = None
  desktop = reg.getDesktop(0)
  for i in xrange(desktop.childCount):
    try:
      app = desktop.getChildAtIndex(i)
    except:
      continue
    if app is None: continue
    if app.name == 'calendar':
      # Get the root pane
      acc = app[1][0][0][1][0]
      break
  return acc

def get_location_label():
  acc = None
  desktop = reg.getDesktop(0)
  frame = pyatspi.findDescendant(
    desktop, 
    lambda x: x.getRole() == pyatspi.ROLE_DIALOG and x.name == 'Open Files',
    breadth_first=True)
  acc = pyatspi.findDescendant(frame, lambda x: x.name == 'Character Coding:')
  return acc
  
if __name__ == "__main__":
  acc = get_location_label()
  print acc
  if acc is None:
    print 'Could not find target accessible'
  else:
    print 'Doing getState %s times' % sampling_size,
    for i in xrange(sampling_size):
      if i % 100 == 0:
        sys.stdout.write('.')
        sys.stdout.flush()
      acc.getState()
    print
    print
    print 'Doing getRelationSet %s times' % sampling_size,
    for i in xrange(sampling_size):
      if i % 100 == 0:
        sys.stdout.write('.')
        sys.stdout.flush()
      acc.getRelationSet()
    print
