Logo Search packages:      
Sourcecode: ldtp version File versions

ldtp.py

#!/usr/bin/env python
#############################################################################
#
#  Linux Desktop Testing Project http://ldtp.freedesktop.org
# 
#  Author:
#     Veerapuram Varadhan <v.varadhan@gmail.com>
#     Prashanth Mohan <prashmohan@gmail.com>
#     Venkateswaran S <wenkat.s@gmail.com>
#     A. Nagappan <nagappan@gmail.com>
# 
#  Copyright 2004 - 2006 Novell, Inc.
# 
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Library General Public
#  License as published by the Free Software Foundation; either
#  version 2 of the License, or (at your option) any later version.
# 
#  This library is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Library General Public License for more details.
# 
#  You should have received a copy of the GNU Library General Public
#  License along with this library; if not, write to the
#  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.
#
#############################################################################

__author__ = "Nagappan A"
__maintainer__ = "Nagappan A"
__version__ = "0.8.0"

import socket, os, types, sys, struct, traceback, time
import threading, re, atexit, random, thread, select, logging, logging.config
from xml.parsers.expat import ExpatError
from xml.dom.minidom import parse, parseString
from xml.sax import saxutils

class command:
      INVALID = 0
      LOG = 1
      STARTLOG = 2
      STOPLOG = 3
      CHECK = 4
      UNCHECK = 5
      MENUCHECK = 6
      MENUUNCHECK = 7
      CLICK = 8
      VERIFYCHECK = 9
      VERIFYUNCHECK = 10
      VERIFYMENUCHECK = 11
      VERIFYMENUUNCHECK = 12
      HIDELIST = 13
      COMBOSELECT = 14
      COMBOSELECTINDEX = 15 
      SELECTINDEX = 16
      ISTEXTSTATEENABLED = 17
      SETTEXTVALUE = 18
      GETTEXTVALUE = 19
      APPENDTEXT = 20
      ACTIVATETEXT = 21
      CUTTEXT = 22
      PASTETEXT = 23
      DELETETEXT = 24
      SELECTTEXTBYNAME = 25
      SELECTTEXTBYINDEXANDREGION = 26
      SHOWLIST = 27
      VERIFYDROPDOWN = 28
      VERIFYHIDELIST = 29
      VERIFYSHOWLIST = 30
      VERIFYSELECT = 31
      VERIFYSETTEXT = 32
      RIGHTCLICK = 33
      GETLABEL = 34
      GETLABELATINDEX = 35
      SELECTPOPUPMENU = 36
      SELECTITEM = 37
      SELECTTEXTITEM = 38
      ISMENUITEMENABLED = 39
      SELECTMENUITEM = 40
      SELECTTAB = 41
      VERIFYPUSHBUTTON = 42
      STATEENABLED = 43
      SETVALUE = 44
      GETVALUE = 45
      VERIFYSETVALUE = 46
      SELECTROW = 47
      SELECTROWINDEX = 48
      SELECTROWPARTIALMATCH = 49
      VERIFYTOGGLED = 50
      ONEDOWN = 51
      ONEUP = 52
      ONERIGHT = 53
      ONELEFT = 54
      SCROLLDOWN = 55
      SCROLLUP = 56
      SCROLLRIGHT = 57
      SCROLLLEFT = 58
      VERIFYSCROLLBAR = 59
      VERIFYSCROLLBARVERTICAL = 60
      VERIFYSCROLLBARHORIZONTAL = 61
      SETMAX = 62
      SETMIN = 63
      INCREASE = 64
      DECREASE = 65
      SELECTPANEL = 66
      SELECTPANELNAME = 67
      GETPANELCHILDCOUNT = 68
      VERIFYTABLECELL = 69
      SETCELLVALUE = 70
      GETCELLVALUE = 71
      SELECTLASTROW = 72
      SELECTLABELSPANELBYNAME = 73
      SETCONTEXT = 74
      RELEASECONTEXT = 75 
      GETSTATUSBARTEXT = 76
      SELECTEVENT = 77
      SELECTEVENTINDEX = 78
      DOESROWEXIST = 79
      DOESMENUITEMEXIST = 80
      LISTSUBMENUS = 81
      CHECKROW = 82
      VERIFYPARTIALMATCH = 83
      GETROWCOUNT = 84
      VERIFYPARTIALTABLECELL = 85
      GRABFOCUS = 86
      VERIFYEVENTEXIST = 87
      EXPANDTABLECELL = 88
      GETTREETABLEROWINDEX = 89
      VERIFYCHECKROW = 90
      VERIFYUNCHECKROW = 91
      VERIFYVISIBLEBUTTONCOUNT = 92
      VERIFYBUTTONCOUNT = 93
      GETEVENTCOUNT = 94
      DOUBLECLICKROW = 95
      GETTABLEROWINDEX = 96
      GETCHARCOUNT = 97
      COPYTEXT = 98
      INSERTTEXT = 99
      UNCHECKROW = 100
      CAPTURETOFILE = 101
      DOUBLECLICK = 102
      GETTEXTPROPERTY = 103
      COMPARETEXTPROPERTY = 104
      CONTAINSTEXTPROPERTY = 105
      SELECTCALENDARDATE = 106
      SELECTTABINDEX = 107
      SORTCOLUMNINDEX = 108
      SORTCOLUMN = 109
      REINITLDTP = 110
      INITAPPMAP = 111
      SETAPPMAP = 112
      VERIFYSLIDER = 113
      VERIFYSLIDERVERTICAL = 114
      VERIFYSLIDERHORIZONTAL = 115
      GETSLIDERVALUE = 116
      VERIFYSTATUSBAR = 117
      VERIFYSTATUSBARVISIBLE = 118
      WAITTILLGUIEXIST = 119
      WAITTILLGUINOTEXIST = 120
      GUIEXIST = 121
      ONWINDOWCREATE = 122
      REMAP = 123
      GETAPPLIST = 124
      GETWINDOWLIST = 125
      GETOBJECTLIST = 126
      GETOBJECTINFO = 127
      GETOBJECTPROPERTY = 128
      BINDTEXT = 129
      GENERATEMOUSEEVENT = 130
      GENERATEKEYEVENT = 131
        MOUSELEFTCLICK = 132
        MOUSERIGHTCLICK = 133
        MOUSEMOVE = 134
      KBDENTER = 135
      SETCURSOR = 136
      GETCURSOR = 137
      GETTABCOUNT = 138
      STOPSCRIPTENGINE = 139
      STARTRECORD = 140
      STOPRECORD = 141
      HASSTATE = 142
      LAUNCHAPP = 143
      SINGLECLICKROW = 144
      SETLOCALE = 145
      INVOKEMENU = 146
      PRESS = 147
      REMOVECALLBACK = 148
      GUITIMEOUT = 149
      OBJTIMEOUT = 150

class error (Exception):
      def __init__ (self, value):
            self.value = value
      def __str__ (self):
            return repr (self.value)

class LdtpExecutionError (Exception):
      def __init__ (self, value):
            self.value = value
      def __str__ (self):
            return repr (self.value)

class ConnectionLost (Exception):
      def __init__ (self, value):
            self.value = value
      def __str__ (self):
            return repr (self.value)

def generatexml (commandId, *args):
      """This Function will parse some information into an LDTP packet
      INPUT: commandId --> command_id
      args --> [,window_name[,object_name[,args...]]]

      OUTPUT: returns a string in the LDTP packet (XML lib2) format"""
      # Argument length
      argsLen = len (args)
      
      _xml = '<?xml version=\"1.0\"?>' ## should this header be there in the packets?
      _xml += '<REQUEST>'
      # Fill action name
      _xml = _xml + '<ACTION>' + str (commandId) + '</ACTION>'
      ldtpDebug = os.getenv ('LDTP_DEBUG')
      if ldtpDebug != None:
            print str (commandId) + ' (',
      if argsLen >= 1:
            _xml = _xml + '<ID>' + saxutils.escape (args [0]) + '</ID>'
      if commandId != command.INITAPPMAP and argsLen >= 2:
            _xml = _xml + '<CONTEXT>' + saxutils.escape (args [1]) + '</CONTEXT>'
            if ldtpDebug != None:
                  print args[1],
      if argsLen >= 3:
            _xml = _xml + '<COMPONENT>' + saxutils.escape (args [2]) + '</COMPONENT>'
            if ldtpDebug != None:
                  print ', ' + args[2],
      if argsLen >= 4:
            _xml = _xml + '<ARGUMENTS>'
            # Fixme: Dirty hack :( start
            if type (args[3]) == list:
                  args = args[3]
                  args.insert (0, '')
                  args.insert (1, '')
                  args.insert (2, '')
                  argsLen = len (args)
            # Fixme: Dirty hack :( end
            for index in range (3, argsLen):
                  if args[index] != None and args[index] != '':
                        _xml = _xml + '<ARGUMENT><![CDATA[' + args[index] + ']]></ARGUMENT>'
                        if ldtpDebug != None:
                              print ', ' + args[index],
            _xml = _xml + '</ARGUMENTS>'
      if commandId == command.INITAPPMAP:
            _xml = _xml + '<ARGUMENTS>'
            _xml = _xml + '<ARGUMENT><![CDATA[' + args[1] + ']]></ARGUMENT>'
            _xml = _xml + '</ARGUMENTS>'
            if ldtpDebug != None:
                  print '( ' + args[1],
      if ldtpDebug != None:
            print ')'
      _xml += '</REQUEST>'
      return _xml

def getText (nodelist):
      rc = ""
      for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                  rc = rc + node.data
      return rc

def getCData (nodelist):
      rc = ""
      for node in nodelist:
            if node.nodeType == node.CDATA_SECTION_NODE:
                  rc = rc + node.data
      return rc

def parseobjectlist (xmldata):
      """Returns the object list"""
      try:
            _objList = None
            dom = parseString (xmldata)
            try:
                  _objList   = dom.getElementsByTagName ('OBJECTLIST')
            except IndexError:
                  raise LdtpExecutionError ('Invalid Object List')
            if _objList == None:
                  raise LdtpExecutionError ('Invalid Object List')
            taglist = []
            for dataelements in _objList:
                  for data in dataelements.getElementsByTagName ('OBJECT'):
                        taglist.append (getText (data.childNodes))
            return taglist
      except ExpatError, msg:
            raise LdtpExecutionError ('Parsing XML error: ' + str (msg))

def parsexml (xmlpacket):
      """Returns the value obtained from the server's return LDTP packet"""

      _statusMsg      = None
      _statusCode     = None
      _serverResponse = None
      _responseType   = None
      _requestId      = None
      _serverResponse = None
      _responseObj    = None
      _serverResponseLen = 0

      try:
            dom = parseString (xmlpacket)
            try:
                  _responseObj  = dom.getElementsByTagName ('RESPONSE')[0]
                  _responseType = 'response'
            except IndexError:
                  try:
                        _responseObj   = dom.getElementsByTagName ('NOTIFICATION')[0]
                        _responseType = 'notification'
                  except IndexError, msg:
                        raise LdtpExecutionError ('Invalid Response')
            try:
                  _responseStatusObj = _responseObj.getElementsByTagName ('STATUS')[0]
                  _statusCode = int (getText (_responseStatusObj.getElementsByTagName ('CODE')[0].childNodes))
                  _statusMsg  = getText (_responseStatusObj.getElementsByTagName ('MESSAGE')[0].childNodes)
            except ValueError:
                  raise LdtpExecutionError ('Invalid Status')
            except IndexError:
                  raise LdtpExecutionError ('Invalid Status')
            try:
                  data = _responseObj.getElementsByTagName ('DATA')[0]
                  _serverResponse    = getCData (data.getElementsByTagName ('VALUE').item (0).childNodes).encode ('utf-8')
                  _serverResponseLen = int (getText (data.getElementsByTagName ('LENGTH')[0].childNodes))
            except ValueError:
                  raise LdtpExecutionError ('Invalid Data Length')
            except IndexError:
                  # Data tag may not be present
                  pass
            try:
                  _requestId  = getText (_responseObj.getElementsByTagName ('ID')[0].childNodes)
            except IndexError:
                  # On notification _requestId will be empty
                  pass
      except ExpatError, msg:
            if msg.code == xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS:
                  return None
            if xml.parsers.expat.ErrorString (msg.code) == xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS:
                  return None
            raise LdtpExecutionError ('Parsing XML error: ' + str (msg))

      # Return all the respective values, let the calling function decide what to do with the values
      return _responseType, (_statusCode, _statusMsg, _requestId), (_serverResponseLen, _serverResponse)

# Send given packet to server
def sendpacket (msg):
      flag = False
      try:
            timedelay = os.getenv ('LDTP_DELAY_CMD')
            sendLck.acquire ()
            if timedelay != None:
                  try:
                        # Delay each command by 'timedelay' seconds
                        time.sleep (int (timedelay))
                  except IndexError:
                        # Default to 5 seconds delay if LDTP_DELAY_CMD
                        # env variable is set
                        time.sleep (5)
            flag = True
            # Get client socket fd based on thread id
            client = _sockFdPool.get (threading.currentThread ())
            
            # Encode the message in UTF-8 so we don't break on extended
            # characters in the application GUIs
            buf = msg.encode ('utf8')
            
            # Pack length (integer value) in network byte order
            msglen = struct.pack ('!i', len (buf))
            # Send message length
            client.send (msglen)
            # Send message
            client.send (buf)
            ldtpDebug = os.getenv ('LDTP_DEBUG')
            if ldtpDebug != None and ldtpDebug == '2':
                  print 'Send packet', buf
            sendLck.release ()
      except socket.error, msg:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  sendLck.release ()
            raise LdtpExecutionError ('Server aborted')

def recvpacket (peek_flag = 0, sockfd = None):
      flag = False
      ldtpDebug = os.getenv ('LDTP_DEBUG')
      try:
            recvLck.acquire ()
            flag = True
            client = None
            # Get client socket fd based on thread id
            if sockfd == None:
                  client = _sockFdPool.get (threading.currentThread ())
            else:
                  client = sockfd
            _responsePacket = None
            client.settimeout (5.0)
            # Hardcoded 4 bytes, as the server sends 4 bytes as packet length
            data = client.recv (4, peek_flag)
            if data == '' or data == None:
                  if flag == True:
                        # Reason for using the flag:
                        # 'Do not call this method when the lock is unlocked.'
                        recvLck.release ()
                  return None
            _packetSize, = struct.unpack('!i', data)
            if peek_flag == 0 and ldtpDebug != None and ldtpDebug == '2':
                  print 'Received packet size', _packetSize
            # MSG_PEEK
                # This flag causes the receive operation to return data from the beginning
            # of the receive queue without removing that data from  the  queue.
            # Thus, a subsequent receive call will return the same data.

            if peek_flag != 0:
                  # MSG_PEEK
                  _responsePacket = client.recv (4 + _packetSize, peek_flag)
            else:
                  _responsePacket = client.recv (_packetSize, peek_flag)
            if peek_flag != 0:
                  _pattern = re.compile ('<\?xml')
                  _searchObj = re.search (_pattern, _responsePacket)
                  _finalPacket = _responsePacket[_searchObj.start () :]
                  _responsePacket = _finalPacket
            recvLck.release ()
            if peek_flag == 0 and ldtpDebug != None and ldtpDebug == '2':
                  print 'Received response Packet', _responsePacket
            return _responsePacket
      except struct.error, msg:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  recvLck.release ()
            raise LdtpExecutionError ('Invalid packet length ' + str (msg))
      except AttributeError, msg:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  recvLck.release ()
            raise LdtpExecutionError ('Error while receiving packet ' + str (msg))
      except socket.timeout:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  recvLck.release ()
            if ldtpDebug != None and ldtpDebug == '2':
                  print 'Timeout'
            return ''
      except socket.error, msg:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  recvLck.release ()
            raise LdtpExecutionError ('Error while receiving packet ' + str (msg))
      except MemoryError, msg:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  recvLck.release ()
            raise LdtpExecutionError ('Error while receiving packet ' + str (msg))
      except:
            if flag == True:
                  # Reason for using the flag:
                  # 'Do not call this method when the lock is unlocked.'
                  recvLck.release ()
            raise LdtpExecutionError ('Error while receiving packet')

def peekresponse ():
      return recvpacket (socket.MSG_PEEK)

def getresponse (packetId):
      while True:
            #print 'DEBUG', 'waiting for readflag', threading.currentThread ()
            _readflag.wait ()
            #print 'DEBUG', 'readflag lock released'
            _readflag.clear ()
            ldtpDebug = os.getenv ('LDTP_DEBUG')
            peekResponsePacket = peekresponse ()
            if peekResponsePacket == None or peekResponsePacket == '':
                  if ldtpDebug != None and ldtpDebug == '2':
                        print 'Peekresponse None'
                  continue
            try:
                  _responseType, _responseStatus, _responseData = parsexml (peekResponsePacket)
            except TypeError, msg:
                  if ldtpDebug != None and ldtpDebug == '2':
                        print 'TypeError', msg
                  continue
            # For precautions, we are just checking, whether the packet is notification or not
            if _responseType == 'notification' or _responseType == None:
                  continue
            if _responseStatus[2] == packetId:
                  if _responseStatus [0] != 0 and ldtpDebug != None:
                        print '*** ' + _responseStatus [1]
                  packet = recvpacket ()
                  # As we have already parsed the packet,
                  # we are just returning the parsed packet
                  return _responseStatus, _responseData

def invokecallback (clientsocket, _responseType, _responseStatus, _responseData):
      packet = recvpacket (sockfd = clientsocket)
      # As we have already parsed the packet,
      # we are just going to invoke the callback function
      clientsock = None
      try:
            # Create a client socket
            clientsock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
      except socket.error,msg:
            raise LdtpExecutionError ('Error while creating UNIX socket  ' + str (msg))
      try:
            # Connect to server socket
            clientsock.connect (socketpath)
      except TypeError:
            raise ConnectionLost ('Environment LDTP_AUTH_SOCK variable not set')

      global _serverpoll
      # Register newly created socket for polling
      _serverpoll.register (clientsock, select.POLLIN)

      # Add new client socket to socket fd pool
      _sockFdPool[threading.currentThread ()] = clientsock
      callback = callback_functions.get (_responseData[1])
      _notificationflag.set ()
      if (callable (callback)):
            callback ()
      # Unregister newly created socket from polling once its completed
      _serverpoll.unregister (clientsock)

def invokeltfxcallback (clientsocket, callback):
      clientsock = None
      try:
            # Create a client socket
            clientsock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
      except socket.error,msg:
            raise LdtpExecutionError ('Error while creating UNIX socket  ' + str (msg))
      try:
            # Connect to server socket
            clientsock.connect (socketpath)
      except TypeError:
            raise ConnectionLost ('Environment LDTP_AUTH_SOCK variable not set')

      global _serverpoll
      # Register newly created socket for polling
      _serverpoll.register (clientsock, select.POLLIN)

      # Add new client socket to socket fd pool
      _sockFdPool[threading.currentThread ()] = clientsock
      _notificationflag.set ()
      if (callable (callback)):
            callback ()
      # Unregister newly created socket from polling once its completed
      _serverpoll.unregister (clientsock)

class PollServer (threading.Thread):
      def __init__ (self):
            threading.Thread.__init__ (self)
            self._events = None
      def run (self):
            try:
                  self.start_polling_server ()
            except:
                  try:
                        raise LdtpExecutionError (str (traceback.format_exc ()))
                  except AttributeError:
                        pass
                  except:
                        pass
      def start_polling_server (self):
            self._serverDisconnected = False
            global _serverpoll
            _serverpoll = select.poll ()
            _serverpoll.register (mainsock, select.POLLIN)

            while True:
                  try:
                        #print 'DEBUG', 'entering poll'
                        self._events = _serverpoll.poll ()
                        #print 'DEBUG', 'poll break'
                  except socket.error, msg:
                        break
                  except:
                        _serverpoll.unregister (mainsock)
                        sys.exit ()
                  try:
                        if self._events == None:
                              break
                        for i in range (0, len (self._events)):
                              #print 'DEBUG', i
                              # if (self._events[i][1] & select.POLLERR or
                              #     self._events[i][1] & select.POLLHUP or
                              #     self._events[i][1] & select.POLLNVAL):
                              #     print 'DEBUG Disconnected', self._events[i][1]
                              #     print 'DEBUG', self._events[i][1] & select.POLLERR
                              #     print 'DEBUG', self._events[i][1] & select.POLLHUP
                              #     print 'DEBUG', self._events[i][1] & select.POLLNVAL
                              #     # If interrupted stop polling
                              #     self._serverDisconnected = True
                              #     break
                              if (self._events[i][1] & select.POLLIN or self._events[i][1] & select.POLLPRI):
                                    _sockFdPool[threading.currentThread ()] = socket.fromfd (self._events[i][0],
                                                                               socket.AF_UNIX,
                                                                               socket.SOCK_STREAM)
                                    try:
                                          # print 'DEBUG', 'handle packet start', \
                                          # self._events[i][1] & select.POLLIN, \
                                          # self._events[i][1] & select.POLLPRI
                                          if self.handle_packet () == None:
                                                self._serverDisconnected = True
                                                # _readflag.set ()
                                                break
                                    except LdtpExecutionError, msg:
                                          self._serverDisconnected = True
                                          # _readflag.set ()
                                          break
                              elif (self._events[i][1] & select.POLLNVAL):
                                    # Unregister newly created socket from polling once its completed
                                    _serverpoll.unregister (self._events[i][0])
                              else:
                                    self._serverDisconnected = True
                                    break
                        if self._serverDisconnected == True:
                              break
                  # Checking this exception due to bug # 333090 comment # 6
                  except TypeError:
                        _serverpoll.unregister (mainsock)
                        sys.exit ()
      def trace_window (self):
            global ltfx_callback_functions
            try:
                  if _notificationflag.isSet () == True:
                        # Let us allow only one callback function to execute at any point of time
                        _notificationflag.wait ()
                        _notificationflag.clear ()
                        if ltfx_callback_functions == {}:
                              _notificationflag.set ()
                              return ''
                        window_info = commands.getstatusoutput ('digwin -c')
                        if window_info[0] != 0:
                              _notificationflag.set ()
                              return ''
                        callback = None
                        regexp = re.compile ('\n+')
                        window_list = regexp.split (window_info[1])
                        for i in ltfx_callback_functions:
                              for j in window_list:
                                    try:
                                          regexp = re.compile (i)
                                          if z.search (j).group () != '':
                                                callback = ltfx_callback_functions.get (i)
                                                thread.start_new_thread (invokeltfxcallback,
                                                                   (_sockFdPool.get (threading.currentThread ()),
                                                                    callback))
                                          else:
                                                _notificationflag.set ()
                                                return ''
                                    except AttributeError:
                                          pass
                        _notificationflag.set ()
                  else:
                        # CPU goes high for some time, if this delay is not there
                        # as the notification packet is still in the Queue, but the
                        # new spanned thread takes some time to receive the notification packet
                        # So this delay is required
                        time.sleep (1)
                  return ''
            except LdtpExecutionError:
                  #_readflag.set ()
                  return ''
            except KeyboardInterrupt:
                  return None
      def handle_packet (self):
            try:
                  self._peekResponsePacket = peekresponse ()
            except KeyboardInterrupt:
                  return None
            _responseType = None
            try:
                  if self._peekResponsePacket == None:
                        # When there is no data to read let us quit
                        return None
                  if self._peekResponsePacket != '':
                        _responseType, _responseStatus, _responseData = parsexml (self._peekResponsePacket)
                        if _responseType == None:
                              return None
                  else:
                        _readflag.set ()
            except TypeError:
                  return ''
            except LdtpExecutionError:
                  #_readflag.set ()
                  return ''
            except KeyboardInterrupt:
                  return None
            try:
                  if _responseType == 'notification':
                        if _notificationflag.isSet () == True:
                              # Let us allow only one callback function to execute at any point of time
                              _notificationflag.wait ()
                              _notificationflag.clear ()
                              thread.start_new_thread (invokecallback,
                                                 (_sockFdPool.get (threading.currentThread ()),
                                                  _responseType, _responseStatus, _responseData))
                        else:
                              # CPU goes high for some time, if this delay is not there
                              # as the notification packet is still in the Queue, but the
                              # new spanned thread takes some time to receive the notification packet
                              # So this delay is required
                              time.sleep (1)
                  else:
                        # print 'DEBUG readflag set 1'
                        _readflag.set ()
            except KeyboardInterrupt:
                  return None
            return ''
      def shutdown (self):
            _readflag.set ()

def shutdown ():
      if threading.activeCount () > 1:
            thread.exit ()
      logging.shutdown ()
      os.kill (os.getpid (), 9)

display = os.getenv ('DISPLAY')

if display == None:
      raise LdtpExecutionError ('Missing DISPLAY environment variable. Running in text mode ?') 

socketpath = '/tmp/ldtp-' + os.getenv ('USER') + '-' + display

ldtpusetcp = False
ldtpserveraddr = None
ldtpserverport = None
if os.environ.has_key("LDTP_SERVER_ADDR"):
      ldtpserveraddr = os.environ["LDTP_SERVER_ADDR"]
      if os.environ.has_key("LDTP_SERVER_PORT"):
            ldtpserverport = int (os.environ["LDTP_SERVER_PORT"])
      else:
            ldtpserverport = 23456
      ldtpusetcp = True

# Init callback functions dictionary
callback_functions = {}

# Init callback functions dictionary
ltfx_callback_functions = {}

# Create read flag
_readflag = threading.Event ()
# Clear the flag by default
_readflag.clear ()

# Create notification flag
_notificationflag = threading.Event ()
# Set the flag by default
_notificationflag.set ()

# Contains poll fd's
_serverpoll = None

# Socket fd pool
_sockFdPool = {}

# Send lock
sendLck = threading.Lock ()
# Recieve lock
recvLck = threading.Lock ()

if socketpath == '':
      raise ConnectionLost ('Server not running')
try:
      # Create a client socket
      mainsock = None
      if ldtpusetcp:
            mainsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
      else:
            mainsock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
except socket.error,msg:
      if ldtpusetcp:
            raise LdtpExecutionError ('Error while creating socket  ' + str (msg))
      else:
            raise LdtpExecutionError ('Error while creating UNIX socket  ' + str (msg))   

# Let us retry connecting to the server for 3 times
retryCount = 0

while True:
      try:
            try:
                  # Connect to server socket
                  if ldtpusetcp:
                        mainsock.connect((ldtpserveraddr, ldtpserverport))
                  else:
                        mainsock.connect (socketpath)
                  break
            except TypeError:
                  raise ConnectionLost ('Environment LDTP_AUTH_SOCK variable not set')
      except socket.error, msg:
            if retryCount == 3:
                  raise ConnectionLost ('Could not establish connection ' + str (msg))
            retryCount += 1
            #If we are not trying to connect to a remote server then we can attempt to
            #startup the ldtp server and then try to re-connect to it.
            if not ldtpusetcp:
                  _pid = os.fork ()
                  if _pid == 0:
                        try:
                              os.execvpe ('ldtp', (), os.environ)
                        except OSError:
                              raise LdtpExecutionError ('ldtp executable not in PATH')
                  else:
                        # Let us wait for 1 second, let the server starts
                        time.sleep (1)

_sockFdPool[threading.currentThread ()] = mainsock

# Start polling server
_pollThread = PollServer ()
_pollThread.setDaemon (True)
_pollThread.start ()
atexit.register (_pollThread.shutdown)
atexit.register (shutdown)

logger  = None
xmlhdlr = None

LDTP_LOG_TESTSTART = 61
LDTP_LOG_TESTEND   = 62
LDTP_LOG_BEGIN     = 63
LDTP_LOG_END       = 64
LDTP_LOG_FAIL      = 65
LDTP_LOG_PASS      = 66
LDTP_LOG_CAUSE     = 67
LDTP_LOG_COMMENT   = 68
LDTP_LOG_GROUPSTART  = 69
LDTP_LOG_GROUPEND    = 70
LDTP_LOG_SCRIPTSTART = 71
LDTP_LOG_SCRIPTEND   = 72
LDTP_LOG_MEMINFO     = 73
LDTP_LOG_CPUINFO     = 74
LDTP_LOG_CATEGORYSTART  = 75
LDTP_LOG_CATEGORYEND    = 76
LDTP_LOG_CATEGORYSTATUS = 77
LDTP_LOG_LOGSTARTTAG    = 78
LDTP_LOG_LOGSTOPTAG     = 79
LDTP_LOG_GROUPSSTATUS   = 80
LDTP_LOG_TIMEINFO       = 81
LDTP_LOG_TOTALTIMEINFO  = 82

logging.addLevelName (LDTP_LOG_TESTSTART, 'TESTSTART')
logging.addLevelName (LDTP_LOG_TESTEND, 'TESTEND')
logging.addLevelName (LDTP_LOG_BEGIN, 'BEGIN')
logging.addLevelName (LDTP_LOG_END, 'END')
logging.addLevelName (LDTP_LOG_FAIL, 'FAIL')
logging.addLevelName (LDTP_LOG_PASS, 'PASS')
logging.addLevelName (LDTP_LOG_CAUSE, 'CAUSE')
logging.addLevelName (LDTP_LOG_COMMENT, 'COMMENT')
logging.addLevelName (LDTP_LOG_GROUPSTART, 'GROUPSTART')
logging.addLevelName (LDTP_LOG_GROUPSSTATUS, 'GROUPSSTATUS')
logging.addLevelName (LDTP_LOG_GROUPEND, 'GROUPEND')
logging.addLevelName (LDTP_LOG_SCRIPTSTART, 'SCRIPTSTART')
logging.addLevelName (LDTP_LOG_SCRIPTEND, 'SCRIPTEND')
logging.addLevelName (LDTP_LOG_MEMINFO, 'MEMINFO')
logging.addLevelName (LDTP_LOG_CPUINFO, 'CPUINFO')
logging.addLevelName (LDTP_LOG_LOGSTARTTAG, 'LOGSTARTTAG')
logging.addLevelName (LDTP_LOG_LOGSTOPTAG, 'LOGSTOPTAG')
logging.addLevelName (LDTP_LOG_TIMEINFO, 'TIMEINFO')
logging.addLevelName (LDTP_LOG_TOTALTIMEINFO, 'TOTALTIMEINFO')
logging.addLevelName (LDTP_LOG_CATEGORYSTART, 'CATEGORYSTART')
logging.addLevelName (LDTP_LOG_CATEGORYEND, 'CATEGORYEND')
logging.addLevelName (LDTP_LOG_CATEGORYSTATUS, 'CATEGORYSTATUS')

class state:
      INVALID = 0
      ACTIVE = 1
      ARMED = 2
      BUSY = 3
      CHECKED = 4
      COLLAPSED = 5
      DEFUNCT = 6
      EDITABLE = 7
      ENABLED = 8
      EXPANDABLE = 9
      EXPANDED = 10
      FOCUSABLE = 11
      FOCUSED = 12
      HORIZONTAL = 13
      ICONIFIED = 14
      MODAL = 15
      MULTI_LINE = 16
      MULTISELECTABLE = 17
      OPAQUE = 18
      PRESSED = 19
      RESIZABLE = 20
      SELECTABLE = 21
      SELECTED = 22
      SENSITIVE = 23
      SHOWING = 24
      SINGLE_LINE = 25
      STALE = 26
      TRANSIENT = 27
      VERTICAL = 28
      VISIBLE = 29
      MANAGES_DESCENDANTS = 30
      INDETERMINATE = 31

def selectevent (windowName, componentName, calendarEventName):
      """Selects the row from the table of calendar events based on the calendar event name specified
      INPUT: selectevent ('<window name>', '<Calendar_view name>', '<calendar event name>')

      OUTPUT: Returns 1 on success and 0 on error."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTEVENT, _requestId, windowName, componentName, calendarEventName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectevent failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
                  
def selecteventindex (windowName, componentName, eventNumber):
      """Select an event from a calendar table using its index. Index for a calendar event starts from 1.
      INPUT: selecteventindex ('<window name>', '<component name>', <event number>)

      OUTPUT: Returns 1 on success and 0 on error."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTEVENTINDEX, _requestId, windowName, componentName, str (eventNumber))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selecteventindex failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
                  
def verifyeventexist (windowName, componentName):
      """verifies whether any events are present in a calendar table
      INPUT: verifyeventexist ('<window name>', '<component name>')

      OUTPUT: Returns 1 on success and 0 on no events."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYEVENTEXIST, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def check (windowName, componentName):
      """Check (tick) the check box state. 
      INPUT: check ('<window name>', '<component name>') 

      OUTPUT: Returns 1 if state is checked, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.CHECK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('check failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
                  
def uncheck (windowName, componentName):
      """Uncheck (un-tick) the check state.
      INPUT: uncheck ('<window name>', '<component name>')

      OUTPUT: Returns 1 if state is unchecked, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.UNCHECK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('uncheck failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def click (windowName, componentName):
      """click on radio button / check box / push button/ combo box/ radio menu item/ toggle button/ radio button.
      INPUT: click ('<window name>', '<component name>')

      OUTPUT: Clicks the component_name."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.CLICK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('click failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def press (windowName, componentName):
      """tell the button to press itself
      INPUT: press ('<window name>', '<component name>')

      OUTPUT: Presses the component_name."""
      try:
            _requestId = str (random.randint (0, sys.maxint))
            _message = generatexml (command.PRESS, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('press failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def menucheck (windowName, componentName):
      """menucheck (tick) the menu item check state. 
      INPUT: menucheck ('<window name>', '<component name>') 

      OUTPUT: Returns 1 if state is checked, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.MENUCHECK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('menucheck failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def menuuncheck (windowName, componentName):
      """menuuncheck (un-tick) the check state.
      INPUT: menuuncheck ('<window name>', '<component name>')

      OUTPUT: Returns 1 if state is unchecked, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.MENUUNCHECK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('menuuncheck failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifycheck (windowName, componentName):
      """Checks the state of check box.
      INPUT: verifycheck ('<window name>', '<component name>')

      OUTPUT: If check box state is checked, then returns 1, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYCHECK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyuncheck (windowName, componentName):
      """Checks the state of check box.
      INPUT: verifyuncheck ('<window name>', '<component name>')

      OUTPUT: If check box state is un-checked, then returns 1, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYUNCHECK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifymenucheck (windowName, menuItem):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYMENUCHECK, _requestId, windowName, menuItem)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifymenuuncheck (windowName, menuItem):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYMENUUNCHECK, _requestId, windowName, menuItem)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifydropdown (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYDROPDOWN, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

# CheckMenuItem Functions

def selectmenuitem (windowName, menuHierarchy):
      """Selects the menu item specified.
      INPUT: selectmenuitem ('<window name>', '<menu hierarchy>')

      OUTPUT: TODO."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTMENUITEM, _requestId, windowName, menuHierarchy)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectmenuitem failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

#  Combobox Functions

def hidelist (windowName, componentName):
      """ Hides combo box drop down list in the current dialog. 
      Suppose in previous operation one testcase has clicked on combo box, 
      its drop down list will be displayed. If further no any operation has 
      been done on that combo box then to close that drop down list 'HideList' 
      action is required.
      INPUT: hidelist ('windowName', 'componentName') 

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.HIDELIST, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('hidelist failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectindex (windowName, componentName, index):
      """ SelectIndex action will select an item from combo box where value of index is pointing to its position in list/menu.
      INPUT: selectindex ('windowName', 'componentName', <index>)

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTINDEX, _requestId, windowName, componentName, str (index))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectindex failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def settextvalue (windowName, componentName, text):
      """puts the text into the component given by the component name
      INPUT: settextvalue ('<window name>', '<component name>', '<text>')

      OUTPUT: returns 1 on success and 0 otherwise"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETTEXTVALUE, _requestId, windowName, componentName, text)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('settextvalue failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def gettextvalue (windowName, componentName, startPosition = None, endPosition = None):
      """
      INPUT: gettextvalue ('<window name>', '<component name>', [start position], [end position])

      OUTPUT: returns 1 on success and 0 otherwise"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETTEXTVALUE, _requestId, windowName, componentName, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('gettextvalue failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def activatetext (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ACTIVATETEXT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('activatetext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def appendtext (windowName, componentName, text):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.APPENDTEXT, _requestId, windowName, componentName, text)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('appendtext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getcursorposition (windowName, componentName):
      """
      INPUT: windowName --> Name in the title bar
             componentName --> Name of the object (TextBox)

      OUTPUT: postion of the text cursor in the object (integer)"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETCURSOR, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getcursorposition failed: ' + _responseStatus [1])
            return long (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setcursorposition (windowName, componentName, position):
      """
      INPUT: windowName --> Name in the title bar
             componentName --> Name of the object (TextBox)
             position --> Position in the TextBox where cursor is to be moved to

      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETCURSOR, _requestId, windowName, componentName, str (position))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setcursorposition failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
      
def capturetofile (windowName, componentName, fileName = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.CAPTURETOFILE, _requestId, windowName, componentName, fileName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('capturetofile failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def showlist (windowName, componentName):
      """ Displays combo box drop down list in the current dialog.
      INPUT: showlist ('windowName', 'componentName')

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SHOWLIST, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('showlist failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verfyhidelist (windowName, componentName):
      """ Verifies if combo box drop down list in the current dialog is not visible.
      INPUT: verfyhidelist ('windowName', 'componentName')

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYHIDELIST, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyselect (windowName, componentName, selectArgument):
      """ VerfySelect action will verify if combo box is set to value given in argument.
      INPUT: verifyselect ('windowName', 'componentName', '<argument>')

      OUTPUT: VerifySelect function will try to find if text box associated with combo box
      is set to value specified in the argument."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSELECT, _requestId, windowName, componentName, selectArgument)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifysettext (windowName, componentName, text):
      """ checks if the text is inserted into the component given by the component name
      INPUT: verifysettext ('<window name>', '<component name>', '<text>')

      OUTPUT: returns 1 if the text is inserted into the specified component else returns 0 """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSETTEXT, _requestId, windowName, componentName, text)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyshowlist (windowName, componentName):
      """ Verifies if combo box drop down list in the current dialog is visible.
      INPUT: verifyshowlist ('windowName', 'componentName')

      OUTPUT: Combo box will generally have a list as its child or a menu as its child. 
      So this function gets object handle of list or menu object, checks if list or 
      menu items of combo box is visible, if yes then return zero else minus one."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSHOWLIST, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def comboselect (windowName, componentName, menuItemName):
      """Select a menu item or list item in a combo box
      INPUT: comboselect ('<window name>', '<component name>', '<menu item name>')

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.COMBOSELECT, _requestId, windowName, componentName, menuItemName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('comboselect failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def comboselectindex (windowName, componentName, index):
      """
      INPUT: comboselectindex ('<window name>', '<component name>', <index>)

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.COMBOSELECTINDEX, _requestId, windowName, componentName, str (index))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('comboselectindex failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def comparetextproperty (windowName, componentName, textProperty, startPosition = None, endPosition = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.COMPARETEXTPROPERTY, _requestId, windowName, componentName, textProperty, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def containstextproperty (windowName, componentName, textProperty, startPosition = None, endPosition = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.CONTAINSTEXTPROPERTY, _requestId, windowName, componentName, textProperty, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def gettextproperty (windowName, componentName, startPosition = None, endPosition = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETTEXTPROPERTY, _requestId, windowName, componentName, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('gettextproperty failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def copytext (windowName, componentName, startPosition = None, endPosition = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.COPYTEXT, _requestId, windowName, componentName, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('copytext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def cuttext (windowName, componentName, startPosition = None, endPosition = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.CUTTEXT, _requestId, windowName, componentName, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('cuttext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def inserttext (windowName, componentName, position, text):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.INSERTTEXT, _requestId, windowName, componentName, str (position), text)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('inserttext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def deletetext (windowName, componentName, startPosition = None, endPosition = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.DELETETEXT, _requestId, windowName, componentName, startPosition, endPosition)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('deletetext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selecttextbyindexandregion (windowName, componentName,
                        startPosition = None, endPosition = None, selectionNum = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if startPosition != None:
            startPosition = str (startPosition)
      if endPosition != None:
            endPosition = str (endPosition)
      if selectionNum != None:
            selectionNum = str (selectionNum)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTTEXTBYINDEXANDREGION, _requestId, windowName, componentName, startPosition, endPosition, selectionNum)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selecttextbyindexandregion failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selecttextbyname (windowName, textName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTTEXTBYNAME, _requestId, windowName, textName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selecttextbyname failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def pastetext (windowName, componentName, position = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      if position != None:
            position = str (position)
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.PASTETEXT, _requestId, windowName, componentName, position)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('pastetext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def expandtablecell (windowName, componentName, position):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.EXPANDTABLECELL, _requestId, windowName, str (position))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('expandtablecell failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getcharcount (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETCHARCOUNT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getcharcount failed: ' + _responseStatus [1])
            return int (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def geteventcount (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETEVENTCOUNT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('geteventcount failed: ' + _responseStatus [1])
            return int (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getlabel (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETLABEL, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getlabel failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getlabelatindex (windowName, componentName, index):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETLABELATINDEX, _requestId, windowName, componentName, index)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getlabelatindex failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectlabelspanelbyname (windowName, labelName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTLABELSPANELBYNAME, _requestId, windowName, labelName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectlabelspanelbyname failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getpanelchildcount (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETPANELCHILDCOUNT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getpanelchildcount failed: ' + _responseStatus [1])
            return int (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getslidervalue (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETSLIDERVALUE, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getslidervalue failed: ' + _responseStatus [1])
            return float (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getstatusbartext (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETSTATUSBARTEXT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getstatusbartext failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def gettreetablerowindex (windowName, componentName, rowText):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETTREETABLEROWINDEX, _requestId, windowName, componentName, rowText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('gettreetablerowindex failed: ' + _responseStatus [1])
            return int (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def grabfocus (windowName, componentName = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            if (componentName != None):
                  _message = generatexml (command.GRABFOCUS, _requestId, windowName, componentName)
            else:
                  _message = generatexml (command.GRABFOCUS, _requestId, windowName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('grabfocus failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def istextstateenabled (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ISTEXTSTATEENABLED, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def listsubmenus (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.LISTSUBMENUS, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('listsubmenus failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def invokemenu (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.INVOKEMENU, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('invokemenu failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def rightclick (windowName, componentName, menuItem, data = None):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.RIGHTCLICK, _requestId, windowName, componentName, menuItem, data)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('rightclick failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectcalendardate (windowName, componentName, day, month, year):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTCALENDARDATE, _requestId, windowName, componentName, str (day), str (month), str (year))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectcalendardate failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectitem (windowName, componentName, item):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTITEM, _requestId, windowName, componentName, item)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectitem failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selecttextitem (windowName, componentName, item):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTEXTITEM, _requestId, windowName, componentName, item)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selecttextitem failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setcellvalue (windowName, componentName, row, column, item):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETCELLVALUE, _requestId, windowName,
                              componentName, str (row), str (column), item)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setcellvalue failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def sortcolumn (windowName, componentName, item):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SORTCOLUMN, _requestId, windowName, componentName, item)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('sortcolumn failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def sortcolumnindex (windowName, componentName, index):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SORTCOLUMNINDEX, _requestId, windowName, componentName, str (index))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('sortcolumnindex failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifybuttoncount (windowName, componentName, count):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYBUTTONCOUNT, _requestId, windowName, componentName, str (count))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

#  General Functions

def waittillguiexist (windowName, componentName = '', guiTimeOut = None):
      """ If the given window name exist, this function returns 1. If window doesnot exist, 
      then this function returns 0. Difference between guiexist and waitguiexist is, 
      waitguiexist waits for maximum 30 seconds. Still the window doesn't appear, 
      then 0 is returned. We can set the environment variable 'GUI_TIMEOUT' to change 
      the default waiting time.
      INPUT: waittillguiexist ('<window name>')

      OUTPUT: returns 1 on success and 0 on no existing window """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            if guiTimeOut and type (guiTimeOut) == int:
                  guiTimeOut = str (guiTimeOut)
            else:
                  guiTimeOut = os.getenv ('GUI_TIMEOUT')
                  if guiTimeOut is None:
                        guiTimeOut = str (30)
            _message = generatexml (command.WAITTILLGUIEXIST, _requestId, windowName, componentName, guiTimeOut)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def waittillguinotexist (windowName, componentName = '', guiTimeOut = None):
      """ If the given window name does not exist, this function returns 1. If window exist, 
      then this function returns 0. Difference between guiexist and waitguinotexist is, 
      waitguinotexist waits for maximum 30 seconds. Still the window does not disappear, 
      then 0 is returned. We can set the environment variable 'GUI_TIMEOUT' to change the 
      default waiting time.
      INPUT: waittillguinotexist ('<window name>')

      OUTPUT: returns 1 on success and 0 on no existing window """
      try:
            if guiTimeOut and type (guiTimeOut) == int:
                  guiTimeOut = str (guiTimeOut)
            else:
                  guiTimeOut = os.getenv ('GUI_TIMEOUT')
                  if guiTimeOut is None:
                        guiTimeOut = str (30)
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.WAITTILLGUINOTEXIST, _requestId, windowName, componentName, guiTimeOut)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def guiexist (windowName, componentName = ''):
      """ If the given window name exist, this function returns 1. If window doesnot exist, 
      then this function returns 0.
      INPUT: guiexist ('<window name>') 

      OUTPUT: returns 1 on success and 0 on no existing window """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GUIEXIST, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def guitimeout (guiTimeOut = 30):
      """ Set gui time out period, If this function called with out arguments, then the default timeout is 30 seconds
      INPUT: guitimeout (30) 

      OUTPUT: returns 1 on success and 0 on failure"""
      try:
            if type (guiTimeOut) == int:
                  guiTimeOut = str (guiTimeOut)
            else:
                  guiTimeOut = os.getenv ('GUI_TIMEOUT')
                  if guiTimeOut is None:
                        guiTimeOut = str (30)
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GUITIMEOUT, _requestId, guiTimeOut)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def objtimeout (objTimeOut = 5):
      """ Set obj time out period, If this function called with out arguments, then the default timeout is 5 seconds
      INPUT: objtimeout (5) 

      OUTPUT: returns 1 on success and 0 on failure"""
      try:
            if type (objTimeOut) == int:
                  objTimeOut = str (objTimeOut)
            else:
                  objTimeOut = os.getenv ('OBJ_TIMEOUT')
                  if objTimeOut is None:
                        objTimeOut = str (5)
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.OBJTIMEOUT, _requestId, objTimeOut)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def objectexist (windowName, componentName):
      """ Check that the given componentName exists in the hierarchy under
      windowName. Returns 1 if componentName exists, 0 otherwise
      INPUT: objectexist ('<window name>', '<component name>')

      OUTPUT: returns 1 if component exists, 0 otherwise """
      try:
            objinfo = getobjectinfo (windowName, componentName)
            if (objinfo):
                  return 1
      except LdtpExecutionError:
            return 0

def initappmap (appmapFileName):
      """ Application map will be loaded
      INPUT: initappmap ('<application map name>')

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.INITAPPMAP, _requestId, appmapFileName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('initappmap failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setappmap (appmapFileName):
      """ A new application map will be loaded. Existing appmap will be unloaded.
      INPUT: setappmap ('<new application map name>')

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETAPPMAP, _requestId, appmapFileName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setappmap failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setcontext (oldContext, newContext):
      """ Set context of window
      INPUT: setcontext ('<old window title>', '<new window title>')

      OUTPUT: TODO"""

      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETCONTEXT, _requestId, oldContext, newContext)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setcontext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def releasecontext (oldContext, newContext):
      """ Release context of window
      INPUT: releasecontext (oldContext, newContext)

      OUTPUT: TODO"""

      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.RELEASECONTEXT, _requestId, oldContext, newContext)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('releasecontext failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def onwindowcreate (windowTitle, callbackFuncName):
      """ On new window creation event, notify
      INPUT: onwindowcreate ('<window title to watch>', <callback function to be called on window create event>)

      OUTPUT: TODO"""

      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ONWINDOWCREATE, _requestId, windowTitle)
            callback_functions [windowTitle] = callbackFuncName
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('onwindowcreate failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def removecallback (windowTitle):
      """ remove reigstered callback
      INPUT: removecallback ('<window title to watch>')

      OUTPUT: TODO"""

      try:
            if callback_functions.has_key (windowTitle):
                  del callback_functions [windowTitle]
                  _requestId  = str (random.randint (0, sys.maxint))
                  _message = generatexml (command.REMOVECALLBACK, _requestId, windowTitle)
                  sendpacket (_message)
                  _responseStatus, _responseData = getresponse (_requestId)
                  if _responseStatus [0] != 0:
                        raise LdtpExecutionError ('removecallback failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def reinitldtp ():
      """ Reinitialize LDTP, which will close existing at-spi connection
      and reestablish it.
      INPUT: reinitldtp ()

      OUTPUT: TODO"""

      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.REINITLDTP, _requestId)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('reinitldtp failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def remap (windowName, componentName = ''):
      """ We can handle dynamically created widgets (meaning widgets created at run time) using 
      this remap function. Calling remap will generate appmap for the given dialog at run 
      time and update the hash table. Then we can access the new widgets.

      Please note that the <application-name> should be same as the one given as the commmand-line 
      argument for appmap generation. 
      INPUT: remap ('<application-name>', '<window name>')

      OUTPUT: It uses the same logic that appmap module uses to generate appmap."""

      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.REMAP, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('remap failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

# Deprecated undoremap function as it is no longer needed

def undoremap (applicationName, windowName):
      """ This function is deprecated and no longer needs to be called.
      This function is a no-op and immediately returns, but exists to
      maintain compatibility with scripts which call it.

      INPUT: undoremap ('<application-name>', 'window name>')
      """
      return 1

#  Log Function

def startldtplog (logFileName, fileOverWrite = 1):
      """ Start logging on the specified file. second arugment is optional and 1 is default value
      0 - Append log to an existing file
      1 - Write log to a new file. If file already exist, 
      then erase existing file content and start log

      INPUT: startldtplog ('<log file name>', [0 or 1])

      OUTPUT: Log file will be created if log file is not present in any case. If second argument is 1, 
      then existing file content will be erased. If second argument is 0, then new logs will be 
      append to existing log.

      It returns 1 on Success and 0 on error  """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.STARTLOG, _requestId, logFileName, str (fileOverWrite))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  pass
            return 1
      except LdtpExecutionError:
            pass

def ldtplog (message, priority = ''):
      """ Logs the message in the log.xml with the tag which can be viewed after the execution of scripts
      INPUT: ldtplog('<Message to be logged>','<tag>')

      OUTPUT: The required message will be logged into the log.xml on execution of scripts
      It returns 1 on Success and 0 on error  """

      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.LOG, _requestId, message, priority)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  pass
            return 1
      except ConnectionLost:
            pass
      except LdtpExecutionError:
            pass

def stopldtplog ():
      """ Stop logging.
      INPUT: stopldtplog()

      OUTPUT: If a log file has been previously opened for logging, that file pointer will be closed. 
      So that the new logging will not be appened to the log file. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.LDTPLOG, _requestId)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  pass
            return 1
      except ConnectionLost:
            pass
      except LdtpExecutionError:
            pass

def setloglevel (level):
      if logger != None:
            #print 'level', level, type (level)
            if type (level) == unicode or type (level) == str:
                  print 'level', level, type (level)
                  regexp = re.compile ('\A' + level, re.IGNORECASE)
                  logLevel = None
                  if regexp.search ('CRITICAL') != None:
                        logLevel = logging.CRITICAL
                  elif regexp.search ('ERROR') != None:
                        logLevel = logging.ERROR
                  elif regexp.search ('WARNING') != None:
                        logLevel = logging.WARNING
                  elif regexp.search ('INFO') != None:
                        logLevel = logging.INFO
                  elif regexp.search ('DEBUG') != None:
                        logLevel = logging.DEBUG
                  if logLevel != None:
                        logger.setLevel (logLevel)
                        return 1
                  else:
                        return 0
            logger.setLevel (level)
            return 1
      else:
            return 0

currentPyVersion = sys.version
regexp = re.compile ('2.5', re.IGNORECASE)
02353 class LdtpLogRecord (logging.LogRecord):
    """
    LogRecord subclass that stores a unique -- transaction -- time
    as an additional attribute
    """
    def __init__ (self, name, level, pathname, lineno, msg, args, exc_info):
          if level == LDTP_LOG_LOGSTARTTAG:
                msg = '<' + saxutils.escape (msg) + '>'
          elif level == LDTP_LOG_LOGSTOPTAG:
                msg = '</' + saxutils.escape (msg) + '>'
          elif level == LDTP_LOG_GROUPSTART:
                msg = '<group name=\"' + saxutils.escape (msg) + '\">'
          elif level == LDTP_LOG_GROUPEND:
                msg = '</group>'
          elif level == LDTP_LOG_CATEGORYSTART:
                msg = '<category name=\"' + saxutils.escape (msg) + '\">'
          elif level == LDTP_LOG_CATEGORYEND:
                msg = '</category>'
          elif level == LDTP_LOG_SCRIPTSTART:
                msg = '<script name=\"' + saxutils.escape (msg) + '\">'
          elif level == LDTP_LOG_SCRIPTEND:
                msg = '</script>'
          elif level == LDTP_LOG_TESTSTART:
                msg = '<test name=\"' + saxutils.escape (msg) + '\">'
          elif level == LDTP_LOG_TESTEND:
                msg = '</test>'
          elif level == LDTP_LOG_BEGIN:
                msg = '<testsuite name=\"' + saxutils.escape (msg) + '\">'
          elif level == LDTP_LOG_END:
                msg = '</testsuite>'
          elif level == LDTP_LOG_PASS:
                msg = '<pass>1</pass>'
          elif level == LDTP_LOG_FAIL:
                msg = '<pass>0</pass>'
          elif level == LDTP_LOG_GROUPSSTATUS:
                msg = '<groupsstatus ' + saxutils.escape (msg) + '></groupsstatus>'
          elif level == LDTP_LOG_CATEGORYSTATUS:
                msg = '<categorystatus ' + saxutils.escape (msg) + '></categorystatus>'
          elif level == LDTP_LOG_TIMEINFO:
                msg = '<timeinfo ' + saxutils.escape (msg) + '></timeinfo>'
          elif level == LDTP_LOG_TOTALTIMEINFO:
                msg = '<totaltimeinfo ' + saxutils.escape (msg) + '></totaltimeinfo>'
          else:
                msg = '<' + logging.getLevelName (level) +'>' + saxutils.escape (msg) + '</' + logging.getLevelName (level) + '>'
          if regexp.search (currentPyVersion) == None:
                logging.LogRecord.__init__ (self, name, level, pathname, lineno, msg, args, exc_info)
          else:
                logging.LogRecord.__init__ (self, name, level, pathname, lineno, msg, args, exc_info, None)

if regexp.search (currentPyVersion) == None:
      def makeRecord (name, level, fn, lno, msg, args, exc_info, func = None, extra = None):
            if type (level) != int and len (msg) == 0:
                  exc_info = args
                  args = msg
                  msg = lno
                  lno = fn
                  fn = level
                  level = name
                  name = logging.getLogger ('XML').name
            return LdtpLogRecord (name, level, fn, lno, msg, args, exc_info)
else:
      def makeRecord (self, name, level, fn, lno, msg, args, exc_info, func = None, extra = None):
            if type (level) != int and len (msg) == 0:
                  exc_info = args
                  args = msg
                  msg = lno
                  lno = fn
                  fn = level
                  level = name
                  name = logging.getLogger ('XML').name
            return LdtpLogRecord (name, level, fn, lno, msg, args, exc_info)

02425 class LdtpLogger (logging.Logger):
    """
    Logger subclass that uses CustomLogRecord as its LogRecord class
    """
    def __init__ (self, name, level=logging.NOTSET):
        logging.Logger.__init__ (self, name, level)

def startlog (logFileName, fileOverWrite = 1):
      """ Start logging on the specified file. second arugment is optional and 1 is default value
      0 - Append log to an existing file
      1 - Write log to a new file. If file already exist, 
      then erase existing file content and start log

      INPUT: startlog ('<log file name>', [0 or 1])

      OUTPUT: Log file will be created if log file is not present in any case. If second argument is 1, 
      then existing file content will be erased. If second argument is 0, then new logs will be 
      append to existing log.

      It returns 1 on Success and 0 on error  """
      try:
            global xmlhdlr, logger

            logging.setLoggerClass (LdtpLogger)
            logger = logging.getLogger ('XML')
            xmlLogMode = 'w'
            if fileOverWrite == 0:
                  xmlLogMode = 'a'
            try:
                  if logFileName [0] == "~":
                        logFileName = os.path.expanduser (logFileName)
                  elif logFileName [0] == ".":
                        logFileName = os.path.abspath (logFileName)
                  xmlhdlr = logging.FileHandler (logFileName, xmlLogMode)
                  logger.addHandler (xmlhdlr)
                  logger.setLevel (logging.WARNING)
                  logger.makeRecord = makeRecord
                  if fileOverWrite == 1:
                        logger.log (LDTP_LOG_LOGSTARTTAG, 'ldtp')
            except IOError:
                  pass
            if xmlhdlr == None:
                  # If xmlhdlr handler is not created, then let us enable this
                  logger.manager.emittedNoHandlerWarning = 1
            return 1
      except LdtpExecutionError, msg:
            pass

def isPriority (priority, givenPriority):
      regexp = re.compile ('\A' + priority, re.IGNORECASE)
      if regexp.search (givenPriority) == None:
            return False
      else:
            return True

def log (message, priority = None):
      """ Logs the message in the log.xml with the tag which can be viewed after the execution of scripts
      INPUT: log('<Message to be logged>','<tag>')

      OUTPUT: The required message will be logged into the log.xml on execution of scripts
      It returns 1 on Success and 0 on error  """

      global logger

      if logger == None:
            # Let us not process anything
            return 1

      if priority == None or isPriority ('DEBUG', priority):
            logger.debug (message)
      elif isPriority ('INFO', priority):
            logger.info (message)
      elif isPriority ('PASS', priority):
            logger.log (LDTP_LOG_PASS, message)
      elif isPriority ('FAIL', priority):
            logger.log (LDTP_LOG_FAIL, message)
      elif isPriority ('ERROR', priority):
            logger.error (message)
      elif isPriority ('CRITICAL', priority):
            logger.critical (message)
      elif isPriority ('WARN', priority):
            logger.warning (message)
      elif isPriority ('CAUSE', priority):
            logger.log (LDTP_LOG_CAUSE, message)
      elif isPriority ('COMMENT', priority):
            logger.log (LDTP_LOG_COMMENT, message)
      elif isPriority ('MEMINFO', priority):
            logger.log (LDTP_LOG_MEMINFO, message)
      elif isPriority ('CPUINFO', priority):
            logger.log (LDTP_LOG_CPUINFO, message)
      elif isPriority ('GROUPSTART', priority):
            logger.log (LDTP_LOG_GROUPSTART, message)
      elif isPriority ('CATEGORYSTART', priority):
            logger.log (LDTP_LOG_CATEGORYSTART, message)
      elif isPriority ('GROUPSSTATUS', priority):
            logger.log (LDTP_LOG_GROUPSSTATUS, message)
      elif isPriority ('GROUPEND', priority):
            logger.log (LDTP_LOG_GROUPEND, message)
      elif isPriority ('CATEGORYEND', priority):
            logger.log (LDTP_LOG_CATEGORYEND, message)
      elif isPriority ('CATEGORYSTATUS', priority):
            logger.log (LDTP_LOG_CATEGORYSTATUS, message)
      elif isPriority ('SCRIPTSTART', priority):
            logger.log (LDTP_LOG_SCRIPTSTART, message)
      elif isPriority ('SCRIPTEND', priority):
            logger.log (LDTP_LOG_SCRIPTEND, message)
      elif isPriority ('TESTSTART', priority):
            logger.log (LDTP_LOG_TESTSTART, message)
      elif isPriority ('TESTEND', priority):
            logger.log (LDTP_LOG_TESTEND, message)
      elif isPriority ('BEGIN', priority):
            logger.log (LDTP_LOG_BEGIN, message)
      elif isPriority ('END', priority):
            logger.log (LDTP_LOG_END, message)
      elif isPriority ('TIMEINFO', priority):
            logger.log (LDTP_LOG_TIMEINFO, message)
      elif isPriority ('TOTALTIMEINFO', priority):
            logger.log (LDTP_LOG_TOTALTIMEINFO, message)
      else:
            logger.debug (message)
      return 1

def addlogger (confFileName):
      logging.config.fileConfig (confFileName)
      return 1

def stoplog (handler = None):
      """ Stop logging.
      INPUT: stoplog()

      OUTPUT: If a log file has been previously opened for logging, that file pointer will be closed. 
      So that the new logging will not be appened to the log file. """
      global xmlhdlr, logger
      if handler != None:
            logger.removeHandler (handler)
      elif xmlhdlr != None:
            logger.log (LDTP_LOG_LOGSTOPTAG, 'ldtp')
            logger.removeHandler (xmlhdlr)
      return 1

def selectrow (windowName, tableName, rowText, nthMatch = 0):
      """Selects the row with the text in the table
      INPUT: selectevent ('<window name>', '<table name>', '<row text to be selected>')

      OUTPUT: Returns 1 on success and 0 on error."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTROW, _requestId, windowName, tableName, rowText, str (nthMatch))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectrow failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
      
def selectrowindex (windowName, tableName, rowIndex):
      """Selects the row with the index in the table
      INPUT: selectevent ('<window name>', '<table name>', <row index>)

      OUTPUT: Returns 1 on success and 0 on error."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTROWINDEX, _requestId, windowName, tableName, str (rowIndex))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectrowindex failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

#  MenuItem Functions

def doesmenuitemexist (windowName, menuHierarchy):
      """ checks if the specified menuitem specified in the menu hierarchy is present or not
      INPUT: doesmenuitemexist ('<window name>', '<menu hierarchy>')

      OUTPUT: Returns 1 if the menuitem is present and 0 otherwise """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.DOESMENUITEMEXIST, _requestId, windowName, menuHierarchy)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

#  Panel Functions

def selectpanel (windowName, componentName, panelNumber):
      """ Select a panel using the panel number in a list of panels
      INPUT: selectpanel ('<window name>', '<component name>', <panel number>)

      OUTPUT: Returns 1 on success and 0 on error """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTPANEL, _requestId, windowName, componentName, str (panelNumber))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectpanel failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectpanelname (windowName, componentName, panelName):
      """ Select a panel using the panel name in a list of panels
      INPUT: selectpanelname ('<window name>', '<component name>', <panel name>)

      OUTPUT: Returns 1 on success and 0 on error """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTPANELNAME, _requestId, windowName, componentName, panelName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectpanelname failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

#  PushButton Functions

def verifypushbutton (windowName, componentName):
      """ Verify whether the given object is push button or not.
      INPUT: verifypushbutton ('<window name>', '<component name>')

      OUTPUT: Returns 1 if object is push button, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYPUSHBUTTON, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def stateenabled (windowName, componentName):
      """ Checks the radio button object state enabled or not
      INPUT: stateenabled ('<window name>', '<component name>')

      OUTPUT: Returns 1 if state is enabled, else 0."""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.STATEENABLED, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

#  ScrollBar Functions

def onedown (windowName, componentName, iterations):
      """ Move the scroll bar down 'n' times, where 'n' is the number of iterations 
      specified in  the argument field.
      INPUT: onedown ('<window name>', '<scroll component name>', '<number of iterations>')

      OUTPUT: Scrolls down if value does not exceed the maximum limit, else fails. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ONEDOWN, _requestId, windowName, componentName, str (iterations))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('onedown failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def oneleft (windowName, componentName, iterations):
      """ Move the (horizontal) scroll bar left 'n' times,
      where 'n' is the number of iterations specified in the argument field.
      INPUT: oneleft ('<window name>', '<scroll component name>', '<number of iterations>')

      OUTPUT: Scrolls left if value does not exceed the maximum limit, else fails. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ONELEFT, _requestId, windowName, componentName, str (iterations))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('oneleft failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def oneright (windowName, componentName, iterations):
      """ Move the (horizontal) scroll bar right 'n' times,
      where 'n' is the number of iterations specified in the argument field.
      INPUT: oneright ('<window name>', '<scroll component name>', '<number of iterations>')

      OUTPUT: Scrolls right if value does not exceed the maximum limit, else fails. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ONERIGHT, _requestId, windowName, componentName, str (iterations))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('oneright failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def oneup (windowName, componentName, iterations):
      """ Move the scroll bar up 'n' times, where 'n' is the number of iterations 
      specified in  the argument field.
      INPUT: oneup ('<window name>', '<scroll component name>', '<number of iterations>')

      OUTPUT: Scrolls up if value does not exceed the maximum limit, else fails. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.ONEUP, _requestId, windowName, componentName, str (iterations))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('oneup failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
    
def scrolldown (windowName, componentName):
      """ Move the (vertical) scroll bar to the bottom.
      INPUT: scrolldown ('<window name>', '<scroll component name>')

      OUTPUT: Returns 1 if action is performed, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SCROLLDOWN, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('scrolldown failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def scrollleft (windowName, componentName):
      """ Move the (horizontal) scroll bar to the left.
      INPUT: scrollleft ('<window name>', '<scroll component name>')

      OUTPUT: Returns 1 if action is performed, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SCROLLLEFT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('scrollleft failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def scrollright (windowName, componentName):
      """ Move the (horizontal) scroll bar to the right.
      INPUT: scrollright ('<window name>', '<scroll component name>')

      OUTPUT: Returns 1 if action is performed, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SCROLLRIGHT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('scrollright failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
      
def scrollup (windowName, componentName):
      """ Move the (vertical) scroll bar to the top.
      INPUT: scrollup ('<window name>', '<scroll component name>')

      OUTPUT: Returns 1 if action is performed, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SCROLLUP, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('scrollup failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifyscrollbar (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSCROLLBAR, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyscrollbarvertical (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSCROLLBARVERTICAL, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyscrollbarhorizontal (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSCROLLBARHORIZONTAL, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyslider (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSLIDER, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyslidervertical (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSLIDERVERTICAL, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifysliderhorizontal (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSLIDERHORIZONTAL, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifystatusbar (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSTATUSBAR, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifystatusbarvisible (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSTATUSBARVISIBLE, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifytoggled (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYTOGGLED, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifyvisiblebuttoncount (windowName, componentName, count):
      """
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYVISIBLEBUTTONCOUNT, _requestId, windowName, componentName, str (count))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

#  Slider Functions

def decrease (windowName, componentName, iterations):
      """ Decrease the value of the slider 'n' times, where 'n' is the number of 
      iterations specified in the argument field.
      INPUT: decrease ('<window name>', '<slider name>', '<number of iterations>')

      OUTPUT: Decreases the value if it does not fall below the minimum limit, else fails. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.DECREASE, _requestId, windowName, componentName, str (iterations))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('decrease failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def increase (windowName, componentName, iterations):
      """ Increase the value of the slider 'n' times, where 'n' is the number of 
      iterations specified in the argument field.
      INPUT: increase ('<window name>', '<slider name>', '<number of iterations>')

      OUTPUT: Increases the value if it does not fall below the minimum limit, else fails. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.INCREASE, _requestId, windowName, componentName, str (iterations))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('increase failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setmax (windowName, componentName):
      """ Set the slider to the maximum value.
      INPUT: setmax ('<window name>', '<slider name>')

      OUTPUT: Returns 1 if action is performed, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETMAX, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setmax failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setmin (windowName, componentName):
      """ Set the slider to the minimum value.
      INPUT: setmin ('<window name>', '<slider name>')

      OUTPUT: Returns 1 if action is performed, else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETMIN, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setmin failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

#  SpinButton Functions

def setvalue (windowName, componentName, value):
      """ Sets the value of the spin button.
      INPUT: setvalue ('<window name>', '<spinbutton name>', '<value>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SETVALUE, _requestId, windowName, componentName, str (value))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setvalue failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getvalue (windowName, componentName):
      """ Gets the value in the spin button.
      INPUT: getvalue ('<window name>', '<spinbutton name>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETVALUE, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getvalue failed: ' + _responseStatus [1])
            return float (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifysetvalue (windowName, componentName, value) :
      """ Verifies the value set in spin button.
      INPUT: verifysetvalue ('<window name>', '<spinbutton name>', '<value>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYSETVALUE, _requestId, windowName, componentName, str (value))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

#  TabControl Functions

def selecttab (windowName, componentName, tabName):
      """ Select the given tab name in the tab list
      INPUT: selecttab ('<window name>', '<tab list name>', '<tab name>')

      OUTPUT: Returns 1 if the tab is selected, otherwise exception will be thrown """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTTAB, _requestId, windowName, componentName, tabName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selecttab failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selecttabindex (windowName, componentName, tabIndex):
      """ Select a particular tab in the list of tabs
      INPUT: selecttabindex ('<windwo name>', '<tab list name>', <index of the tab>)

      OUTPUT: Returns 1 if the tab is selected, otherwise exception will be thrown """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTTABINDEX, _requestId, windowName, componentName, str (tabIndex))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selecttabindex failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def gettabcount (windowName, componentName):
      """ Gets the number of tabs in an object
      INPUT: gettabcount ('<window name>', '<object name>')
             e.g. getttabcount ('terminal','ptl0')

      OUTPUT: Returns the number of tabs in the object """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETTABCOUNT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('gettabcount failed: ' + _responseStatus [1])
            return long(_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def checkrow (windowName, componentName, rowIndex, columnIndex = 0):
      """ checks the row with the given index value in table. This can take an 
      optional column index and perform the action on that particular column. 
      If the column index is not given, 0 is taken as the default value.
      Index value starts from 0.
      INPUT: checkrow ('<window name>', '<table name>', <row index>, <col index>)

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.CHECKROW, _requestId, windowName, componentName, str (rowIndex), str (columnIndex))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('checkrow failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifycheckrow (windowName, componentName, rowIndex, columnIndex = 0):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYCHECKROW, _requestId, windowName, componentName, str (rowIndex), str (columnIndex))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def doesrowexist (windowName, componentName, rowText):
      """ Checks whether the table contains any row with any of its cell containing 
      the given string as its value.Please note that it checks for an exact match.
      INPUT: doesrowexist ('<window name>', '<table name>', '<string to be matched>')

      OUTPUT: Returns 1 if there are rows with the given string in any of its cell else 0. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.DOESROWEXIST, _requestId, windowName, componentName, rowText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0
    
def doubleclick (windowName, componentName):
      """
      INPUT: doubleclick ('<window name>', '<table name>')

      OUTPUT: Returns 1 on success and exception on error"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.DOUBLECLICK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('doubleclick failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def doubleclickrow (windowName, componentName, rowText):
      """ Double clicks the row in table whose first column's (0th column) value 
      is same as the contents of the third argument in the function call.
      INPUT: doubleclickrow ('<window name>', '<table name>', '<value of row in first column>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.DOUBLECLICKROW, _requestId, windowName, componentName, rowText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('doubleclickrow failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def singleclickrow (windowName, componentName, rowText):
      """ Single clicks the row in the table whose first column's (0th column) value is the
      the same as the contents of the 'rowText' or third arguement in the function call.
      INPUT: singleclickrow ('<window name>', '<table name>', '<value of the header/top column>')
      
      OUTPUT: Returns 1 on success and 0 on error."""
      try:
            _requestId = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SINGLECLICKROW, _requestId, windowName, componentName, rowText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError('singleclickrow failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getcellvalue (windowName, componentName, row, column = 0):
      """ returns the text in a cell at given row and column of a tree table
      INPUT: getcellvalue ('<window name>', '<component name>', '<row>', '<column>')

      OUTPUT: returns the string """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETCELLVALUE, _requestId, windowName, componentName, str (row), str (column))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getcellvalue failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getrowcount (windowName, componentName):
      """ returns the number of rows in the table
      INPUT: getrowcount ('<window name>', '<table name>' )

      OUTPUT: Returns the number of rows present in the table mentioned """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETROWCOUNT, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getrowcount failed: ' + _responseStatus [1])
            return int (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))
    
def gettablerowindex (windowName, componentName, rowText):
      """ Returns the id of the row containing the given <cellvalue>
      INPUT: gettablerowindex ('<window name>','<tablename>','<cellvalue>')

      OUTPUT: Return id of the row containing the given cell value, if it is found else return -1 """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETTABLEROWINDEX, _requestId, windowName, componentName, rowText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return -1L
            return int (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectlastrow (windowName, componentName):
      """ Selects the last row of a table.
      INPUT: selectlastrow ('<window name>', '<table name>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTLASTROW, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectlastrow failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def selectrowpartialmatch (windowName, componentName, rowPartialText):
      """ selects the row having cell that contains the given text.
      INPUT: selectrowpartialmatch ('<window name>', '<tree table name>', '<texttobesearchedfor>')

      OUTPUT: returns 1 on success and throws an exception on error """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.SELECTROWPARTIALMATCH, _requestId, windowName, componentName, rowPartialText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('selectrowpartialmatch failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifypartialmatch (windowName, componentName, rowPartialText):
      """ 
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYPARTIALMATCH, _requestId, windowName, componentName, rowPartialText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifypartialtablecell (windowName, componentName, rowIndex, columnIndex, rowPartialText):
      """ 
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYPARTIALTABLECELL, _requestId, windowName, componentName,
                              str (rowIndex), str (columnIndex), rowPartialText)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def uncheckrow (windowName, componentName, rowIndex, columnIndex = 0):
      """ Unchecks the row with the given index value in table. This can take an 
      optional column index and perform the action on that particular column. 
      If the column index is not given, 0 is taken as the default value. Index 
      value starts from 0.
      INPUT: uncheckrow ('<window name>', '<table name>', <row index>, [<col index>])

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.UNCHECKROW, _requestId, windowName, componentName, str (rowIndex), str (columnIndex))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('uncheckrow failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def verifyuncheckrow (windowName, componentName, rowIndex, columnIndex = 0):
      """ 
      INPUT: TODO

      OUTPUT: TODO """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYUNCHECKROW, _requestId, windowName, componentName, str (rowIndex), str (columnIndex))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifytablecell (windowName, componentName, rowIndex, columnIndex, textToCompare):
      """ Verifies the tablecell value with the String Passed ie., fifth argument
      INPUT: verifytablecell ('<window name>', '<table name>', '<row no>','<column no>','<string to be compared>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYTABLECELL, _requestId, windowName, componentName,
                              str (rowIndex), str (columnIndex), textToCompare)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0

def verifypartialcellvalue (windowName, componentName, rowIndex, columnIndex, partialTextToCompare):
      """ Verifies the tablecell value with the sub String Passed ie., fifth argument
      INPUT: verifypartialtablecell ('<window name>', '<table name>', '<row no>','<column no>','< sub string to be compared>')

      OUTPUT: Returns 1 on success and 0 on error. """
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.VERIFYPARTIALCELLVALUE, _requestId, windowName, componentName,
                              str (rowIndex), str (columnIndex), partialTextToCompare)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError, msg:
            return 0
    
def getwindowlist ():
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETWINDOWLIST, _requestId)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getwindowlist failed: ' + _responseStatus [1])
            return parseobjectlist (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getapplist ():
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETAPPLIST, _requestId)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getapplist failed: ' + _responseStatus [1])
            return parseobjectlist (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getobjectlist (windowName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETOBJECTLIST, _requestId, windowName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getobjectlist failed: ' + _responseStatus [1])
            return parseobjectlist (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getobjectinfo (windowName, componentName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETOBJECTINFO, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getobjectinfo failed: ' + _responseStatus [1])
            return parseobjectlist (_responseData[1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def getobjectproperty (windowName, componentName, propertyName):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GETOBJECTPROPERTY, _requestId, windowName, componentName, propertyName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('getobjectproperty failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def setlocale (locale = None):
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = None
            if locale == None:
                  _message = generatexml (command.SETLOCALE, _requestId, os.getenv ('LANG'))
            else:
                  os.environ ['LANG'] = locale
                  _message = generatexml (command.SETLOCALE, _requestId, locale)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('setlocale failed: ' + _responseStatus [1])
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))      

def bindtext (packageName, localeDir, mode = 'mo'):
      """
      INPUT: TODO

      OUTPUT: TODO"""
      try:
            setlocale
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.BINDTEXT, _requestId, packageName, localeDir, mode)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('bindtext failed: ' + _responseStatus [1])
            return _responseData[1]
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def generatemouseevent (x, y, eventType = 'b1c'):
      """
      INPUT:
      X - Coordinate
      Y - Coordinate
      eventType

      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GENERATEMOUSEEVENT, _requestId, str (x), str (y), eventType)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('generatemouseevent failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def mouseleftclick (windowName, componentName):
      """
      INPUT: windowName --> Window containing object
               componentName --> object's name

      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.MOUSELEFTCLICK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('mouseleftclick failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def mouserightclick (windowName, componentName):
      """
      INPUT: windowName --> Window containing object
               componentName --> object's name

      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.MOUSERIGHTCLICK, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('mouserightclick failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def mousemove (windowName, componentName):
      """
      INPUT: windowName --> Window containing object
               componentName --> object's name

      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.MOUSEMOVE, _requestId, windowName, componentName)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('mousemove failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def enterstring (windowName, componentName, data):
      """
      INPUT: windowName --> Window containing object
               componentName --> object's name
             data --> string to be simulated as entered from keyboard
                      Special non printing characters are enter within '<' and '>'
                  e.g. <capslock>,<ctrl>, etc while other characters are entered
                  in a straight forward fashion. e.g. '<ctrl>Nwww.google.com'    
      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.KBDENTER, _requestId, windowName, componentName, data)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('enterstring failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def generatekeyevent (data):
      """
      INPUT: data --> string to be simulated as entered from keyboard
      Special non printing characters are enter within '<' and '>'
      e.g. <capslock>,<ctrl>, etc while other characters are entered
      in a straight forward fashion. e.g. '<ctrl>Nwww.google.com'    
      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.GENERATEKEYEVENT, _requestId, data)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  raise LdtpExecutionError ('generatekeyevent failed: ' + _responseStatus [1])
            return 1
      except LdtpExecutionError, msg:
            raise LdtpExecutionError (str (msg))

def stopscriptengine ():
      """
      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.STOPSCRIPTENGINE, _requestId)
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
      except LdtpExecutionError:
            pass

def hasstate (windowName, componentName, state):
      """
      INPUT: TODO
      OUTPUT: TODO"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            p = re.compile(r'\W+')
            _message = generatexml (command.HASSTATE, _requestId, windowName, componentName, str (state))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
            if _responseStatus [0] != 0:
                  return 0
            return 1
      except LdtpExecutionError:
            return 0

def launchapp (appname, env = 1):
      """
      OUTPUT: None"""
      try:
            _requestId  = str (random.randint (0, sys.maxint))
            _message = generatexml (command.LAUNCHAPP, _requestId, appname, str (env))
            sendpacket (_message)
            _responseStatus, _responseData = getresponse (_requestId)
      except LdtpExecutionError:
            pass

Generated by  Doxygen 1.6.0   Back to index