signature:
def getapplist ( self ) :
    """Get all accessibility application name that are currently running
 @ return : list of appliction name of string type on success .
 @ rtype : list"""

implementation:
app_list = [ ]
# Update apps list , before parsing the list
self . _update_apps ( )
for gui in self . _running_apps :
    name = gui . localizedName ( )
    # default type was objc . pyobjc _ unicode
    # convert to Unicode , else exception is thrown
    # TypeError : " cannot marshal < type ' objc . pyobjc _ unicode ' > objects "
    try :
        name = unicode ( name )
    except NameError :
        name = str ( name )
    except UnicodeEncodeError :
        pass
    app_list . append ( name )
# Return unique application list
return list ( set ( app_list ) )


signature:
def startprocessmonitor ( self , process_name , interval = 2 ) :
    """Start memory and CPU monitoring , with the time interval between
 each process scan
 @ param process _ name : Process name , ex : firefox - bin .
 @ type process _ name : string
 @ param interval : Time interval between each process scan
 @ type interval : double
 @ return : 1 on success
 @ rtype : integer"""

implementation:
if process_name in self . _process_stats : # Stop previously running instance
# At any point , only one process name can be tracked
# If an instance already exist , then stop it
    self . _process_stats [ process_name ] . stop ( )
# Create an instance of process stat
self . _process_stats [ process_name ] = ProcessStats ( process_name , interval )
# start monitoring the process
self . _process_stats [ process_name ] . start ( )
return 1


signature:
def stopprocessmonitor ( self , process_name ) :
    """Stop memory and CPU monitoring
 @ param process _ name : Process name , ex : firefox - bin .
 @ type process _ name : string
 @ return : 1 on success
 @ rtype : integer"""

implementation:
if process_name in self . _process_stats : # Stop monitoring process
    self . _process_stats [ process_name ] . stop ( )
return 1


signature:
def getcpustat ( self , process_name ) :
    """get CPU stat for the give process name
 @ param process _ name : Process name , ex : firefox - bin .
 @ type process _ name : string
 @ return : cpu stat list on success , else empty list
 If same process name , running multiple instance ,
 get the stat of all the process CPU usage
 @ rtype : list"""

implementation:
# Create an instance of process stat
_stat_inst = ProcessStats ( process_name )
_stat_list = [ ]
for p in _stat_inst . get_cpu_memory_stat ( ) :
    try :
        _stat_list . append ( p . get_cpu_percent ( ) )
    except psutil . AccessDenied :
        pass
return _stat_list


signature:
def getmemorystat ( self , process_name ) :
    """get memory stat
 @ param process _ name : Process name , ex : firefox - bin .
 @ type process _ name : string
 @ return : memory stat list on success , else empty list
 If same process name , running multiple instance ,
 get the stat of all the process memory usage
 @ rtype : list"""

implementation:
# Create an instance of process stat
_stat_inst = ProcessStats ( process_name )
_stat_list = [ ]
for p in _stat_inst . get_cpu_memory_stat ( ) : # Memory percent returned with 17 decimal values
# ex : 0.16908645629882812 , round it to 2 decimal values
# as 0.03
    try :
        _stat_list . append ( round ( p . get_memory_percent ( ) , 2 ) )
    except psutil . AccessDenied :
        pass
return _stat_list


signature:
def getobjectlist ( self , window_name ) :
    """Get list of items in given GUI .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ return : list of items in LDTP naming convention .
 @ rtype : list"""

implementation:
try :
    window_handle , name , app = self . _get_window_handle ( window_name , True )
    object_list = self . _get_appmap ( window_handle , name , True )
except atomac . _a11y . ErrorInvalidUIElement : # During the test , when the window closed and reopened
# ErrorInvalidUIElement exception will be thrown
    self . _windows = { }
    # Call the method again , after updating apps
    window_handle , name , app = self . _get_window_handle ( window_name , True )
    object_list = self . _get_appmap ( window_handle , name , True )
return object_list . keys ( )


signature:
def getobjectinfo ( self , window_name , object_name ) :
    """Get object properties .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : list of properties
 @ rtype : list"""

implementation:
try :
    obj_info = self . _get_object_map ( window_name , object_name , wait_for_object = False )
except atomac . _a11y . ErrorInvalidUIElement : # During the test , when the window closed and reopened
# ErrorInvalidUIElement exception will be thrown
    self . _windows = { }
    # Call the method again , after updating apps
    obj_info = self . _get_object_map ( window_name , object_name , wait_for_object = False )
props = [ ]
if obj_info :
    for obj_prop in obj_info . keys ( ) :
        if not obj_info [ obj_prop ] or obj_prop == "obj" : # Don ' t add object handle to the list
            continue
        props . append ( obj_prop )
return props


signature:
def getobjectproperty ( self , window_name , object_name , prop ) :
    """Get object property value .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param prop : property name .
 @ type prop : string
 @ return : property
 @ rtype : string"""

implementation:
try :
    obj_info = self . _get_object_map ( window_name , object_name , wait_for_object = False )
except atomac . _a11y . ErrorInvalidUIElement : # During the test , when the window closed and reopened
# ErrorInvalidUIElement exception will be thrown
    self . _windows = { }
    # Call the method again , after updating apps
    obj_info = self . _get_object_map ( window_name , object_name , wait_for_object = False )
if obj_info and prop != "obj" and prop in obj_info :
    if prop == "class" : # ldtp _ class _ type are compatible with Linux and Windows class name
    # If defined class name exist return that ,
    # else return as it is
        return ldtp_class_type . get ( obj_info [ prop ] , obj_info [ prop ] )
    else :
        return obj_info [ prop ]
raise LdtpServerException ( 'Unknown property "%s" in %s' % ( prop , object_name ) )


signature:
def getchild ( self , window_name , child_name = '' , role = '' , parent = '' ) :
    """Gets the list of object available in the window , which matches
 component name or role name or both .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param child _ name : Child name to search for .
 @ type child _ name : string
 @ param role : role name to search for , or an empty string for wildcard .
 @ type role : string
 @ param parent : parent name to search for , or an empty string for wildcard .
 @ type role : string
 @ return : list of matched children names
 @ rtype : list"""

implementation:
matches = [ ]
if role :
    role = re . sub ( ' ' , '_' , role )
self . _windows = { }
if parent and ( child_name or role ) :
    _window_handle , _window_name = self . _get_window_handle ( window_name ) [ 0 : 2 ]
    if not _window_handle :
        raise LdtpServerException ( 'Unable to find window "%s"' % window_name )
    appmap = self . _get_appmap ( _window_handle , _window_name )
    obj = self . _get_object_map ( window_name , parent )
    def _get_all_children_under_obj ( obj , child_list ) :
        if role and obj [ 'class' ] == role :
            child_list . append ( obj [ 'label' ] )
        elif child_name and self . _match_name_to_appmap ( child_name , obj ) :
            child_list . append ( obj [ 'label' ] )
        if obj :
            children = obj [ 'children' ]
        if not children :
            return child_list
        for child in children . split ( ) :
            return _get_all_children_under_obj ( appmap [ child ] , child_list )
    matches = _get_all_children_under_obj ( obj , [ ] )
    if not matches :
        if child_name :
            _name = 'name "%s" ' % child_name
        if role :
            _role = 'role "%s" ' % role
        if parent :
            _parent = 'parent "%s"' % parent
        exception = 'Could not find a child %s%s%s' % ( _name , _role , _parent )
        raise LdtpServerException ( exception )
    return matches
_window_handle , _window_name = self . _get_window_handle ( window_name ) [ 0 : 2 ]
if not _window_handle :
    raise LdtpServerException ( 'Unable to find window "%s"' % window_name )
appmap = self . _get_appmap ( _window_handle , _window_name )
for name in appmap . keys ( ) :
    obj = appmap [ name ]
    # When only role arg is passed
    if role and not child_name and obj [ 'class' ] == role :
        matches . append ( name )
    # When parent and child _ name arg is passed
    if parent and child_name and not role and self . _match_name_to_appmap ( parent , obj ) :
        matches . append ( name )
    # When only child _ name arg is passed
    if child_name and not role and self . _match_name_to_appmap ( child_name , obj ) :
        return name
        matches . append ( name )
    # When role and child _ name args are passed
    if role and child_name and obj [ 'class' ] == role and self . _match_name_to_appmap ( child_name , obj ) :
        matches . append ( name )
if not matches :
    _name = ''
    _role = ''
    _parent = ''
    if child_name :
        _name = 'name "%s" ' % child_name
    if role :
        _role = 'role "%s" ' % role
    if parent :
        _parent = 'parent "%s"' % parent
    exception = 'Could not find a child %s%s%s' % ( _name , _role , _parent )
    raise LdtpServerException ( exception )
return matches


signature:
def launchapp ( self , cmd , args = [ ] , delay = 0 , env = 1 , lang = "C" ) :
    """Launch application .
 @ param cmd : Command line string to execute .
 @ type cmd : string
 @ param args : Arguments to the application
 @ type args : list
 @ param delay : Delay after the application is launched
 @ type delay : int
 @ param env : GNOME accessibility environment to be set or not
 @ type env : int
 @ param lang : Application language to be used
 @ type lang : string
 @ return : 1 on success
 @ rtype : integer
 @ raise LdtpServerException : When command fails"""

implementation:
try :
    atomac . NativeUIElement . launchAppByBundleId ( cmd )
    return 1
except RuntimeError :
    if atomac . NativeUIElement . launchAppByBundlePath ( cmd , args ) : # Let us wait so that the application launches
        try :
            time . sleep ( int ( delay ) )
        except ValueError :
            time . sleep ( 5 )
        return 1
    else :
        raise LdtpServerException ( u"Unable to find app '%s'" % cmd )


signature:
def activatewindow ( self , window_name ) :
    """Activate window .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
window_handle = self . _get_window_handle ( window_name )
self . _grabfocus ( window_handle )
return 1


signature:
def click ( self , window_name , object_name ) :
    """Click item .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
size = self . _getobjectsize ( object_handle )
self . _grabfocus ( object_handle )
self . wait ( 0.5 )
# If object doesn ' t support Press , trying clicking with the object
# coordinates , where size = ( x , y , width , height )
# click on center of the widget
# Noticed this issue on clicking AXImage
# click ( ' Instruments * ' , ' Automation ' )
self . generatemouseevent ( size [ 0 ] + size [ 2 ] / 2 , size [ 1 ] + size [ 3 ] / 2 , "b1c" )
return 1


signature:
def getallstates ( self , window_name , object_name ) :
    """Get all states of given object
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : list of string on success .
 @ rtype : list"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
_obj_states = [ ]
if object_handle . AXEnabled :
    _obj_states . append ( "enabled" )
if object_handle . AXFocused :
    _obj_states . append ( "focused" )
else :
    try :
        if object_handle . AXFocused :
            _obj_states . append ( "focusable" )
    except :
        pass
if re . match ( "AXCheckBox" , object_handle . AXRole , re . M | re . U | re . L ) or re . match ( "AXRadioButton" , object_handle . AXRole , re . M | re . U | re . L ) :
    if object_handle . AXValue :
        _obj_states . append ( "checked" )
return _obj_states


signature:
def hasstate ( self , window_name , object_name , state , guiTimeOut = 0 ) :
    """has state
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ type window _ name : string
 @ param state : State of the current object .
 @ type object _ name : string
 @ param guiTimeOut : Wait timeout in seconds
 @ type guiTimeOut : integer
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name )
    if state == "enabled" :
        return int ( object_handle . AXEnabled )
    elif state == "focused" :
        return int ( object_handle . AXFocused )
    elif state == "focusable" :
        return int ( object_handle . AXFocused )
    elif state == "checked" :
        if re . match ( "AXCheckBox" , object_handle . AXRole , re . M | re . U | re . L ) or re . match ( "AXRadioButton" , object_handle . AXRole , re . M | re . U | re . L ) :
            if object_handle . AXValue :
                return 1
except :
    pass
return 0


signature:
def getobjectsize ( self , window_name , object_name = None ) :
    """Get object size
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : x , y , width , height on success .
 @ rtype : list"""

implementation:
if not object_name :
    handle , name , app = self . _get_window_handle ( window_name )
else :
    handle = self . _get_object_handle ( window_name , object_name )
return self . _getobjectsize ( handle )


signature:
def grabfocus ( self , window_name , object_name = None ) :
    """Grab focus .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
if not object_name :
    handle , name , app = self . _get_window_handle ( window_name )
else :
    handle = self . _get_object_handle ( window_name , object_name )
return self . _grabfocus ( handle )


signature:
def guiexist ( self , window_name , object_name = None ) :
    """Checks whether a window or component exists .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    self . _windows = { }
    if not object_name :
        handle , name , app = self . _get_window_handle ( window_name , False )
    else :
        handle = self . _get_object_handle ( window_name , object_name , wait_for_object = False , force_remap = True )
    # If window and / or object exist , exception will not be thrown
    # blindly return 1
    return 1
except LdtpServerException :
    pass
return 0


signature:
def waittillguiexist ( self , window_name , object_name = '' , guiTimeOut = 30 , state = '' ) :
    """Wait till a window or component exists .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param guiTimeOut : Wait timeout in seconds
 @ type guiTimeOut : integer
 @ param state : Object state used only when object _ name is provided .
 @ type object _ name : string
 @ return : 1 if GUI was found , 0 if not .
 @ rtype : integer"""

implementation:
timeout = 0
while timeout < guiTimeOut :
    if self . guiexist ( window_name , object_name ) :
        return 1
    # Wait 1 second before retrying
    time . sleep ( 1 )
    timeout += 1
# Object and / or window doesn ' t appear within the timeout period
return 0


signature:
def waittillguinotexist ( self , window_name , object_name = '' , guiTimeOut = 30 ) :
    """Wait till a window does not exist .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param guiTimeOut : Wait timeout in seconds
 @ type guiTimeOut : integer
 @ return : 1 if GUI has gone away , 0 if not .
 @ rtype : integer"""

implementation:
timeout = 0
while timeout < guiTimeOut :
    if not self . guiexist ( window_name , object_name ) :
        return 1
    # Wait 1 second before retrying
    time . sleep ( 1 )
    timeout += 1
# Object and / or window still appears within the timeout period
return 0


signature:
def objectexist ( self , window_name , object_name ) :
    """Checks whether a window or component exists .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 if GUI was found , 0 if not .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name )
    return 1
except LdtpServerException :
    return 0


signature:
def stateenabled ( self , window_name , object_name ) :
    """Check whether an object state is enabled or not
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success 0 on failure .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name )
    if object_handle . AXEnabled :
        return 1
except LdtpServerException :
    pass
return 0


signature:
def check ( self , window_name , object_name ) :
    """Check item .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
# FIXME : Check for object type
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
if object_handle . AXValue == 1 : # Already checked
    return 1
# AXPress doesn ' t work with Instruments
# So did the following work around
self . _grabfocus ( object_handle )
x , y , width , height = self . _getobjectsize ( object_handle )
# Mouse left click on the object
# Note : x + width / 2 , y + height / 2 doesn ' t work
self . generatemouseevent ( x + width / 2 , y + height / 2 , "b1c" )
return 1


signature:
def verifycheck ( self , window_name , object_name ) :
    """Verify check item .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success 0 on failure .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name , wait_for_object = False )
    if object_handle . AXValue == 1 :
        return 1
except LdtpServerException :
    pass
return 0


signature:
def getaccesskey ( self , window_name , object_name ) :
    """Get access key of given object
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : access key in string format on success , else LdtpExecutionError on failure .
 @ rtype : string"""

implementation:
# Used http : / / www . danrodney . com / mac / as reference for
# mapping keys with specific control
# In Mac noticed ( in accessibility inspector ) only menu had access keys
# so , get the menu _ handle of given object and
# return the access key
menu_handle = self . _get_menu_handle ( window_name , object_name )
key = menu_handle . AXMenuItemCmdChar
modifiers = menu_handle . AXMenuItemCmdModifiers
glpyh = menu_handle . AXMenuItemCmdGlyph
virtual_key = menu_handle . AXMenuItemCmdVirtualKey
modifiers_type = ""
if modifiers == 0 :
    modifiers_type = "<command>"
elif modifiers == 1 :
    modifiers_type = "<shift><command>"
elif modifiers == 2 :
    modifiers_type = "<option><command>"
elif modifiers == 3 :
    modifiers_type = "<option><shift><command>"
elif modifiers == 4 :
    modifiers_type = "<ctrl><command>"
elif modifiers == 6 :
    modifiers_type = "<ctrl><option><command>"
# Scroll up
if virtual_key == 115 and glpyh == 102 :
    modifiers = "<option>"
    key = "<cursor_left>"
# Scroll down
elif virtual_key == 119 and glpyh == 105 :
    modifiers = "<option>"
    key = "<right>"
# Page up
elif virtual_key == 116 and glpyh == 98 :
    modifiers = "<option>"
    key = "<up>"
# Page down
elif virtual_key == 121 and glpyh == 107 :
    modifiers = "<option>"
    key = "<down>"
# Line up
elif virtual_key == 126 and glpyh == 104 :
    key = "<up>"
# Line down
elif virtual_key == 125 and glpyh == 106 :
    key = "<down>"
# Noticed in Google Chrome navigating next tab
elif virtual_key == 124 and glpyh == 101 :
    key = "<right>"
# Noticed in Google Chrome navigating previous tab
elif virtual_key == 123 and glpyh == 100 :
    key = "<left>"
# List application in a window to Force Quit
elif virtual_key == 53 and glpyh == 27 :
    key = "<escape>"
# FIXME :
# * Instruments Menu View - > Run Browser
# modifiers = = 12 virtual _ key = = 48 glpyh = = 2
# * Terminal Menu Edit - > Start Dictation
# fn fn - glpyh = = 148 modifiers = = 24
# * Menu Chrome - > Clear Browsing Data in Google Chrome
# virtual _ key = = 51 glpyh = = 23 [ Delete Left ( like Backspace on a PC ) ]
if not key :
    raise LdtpServerException ( "No access key associated" )
return modifiers_type + key


signature:
def paste ( cls ) :
    """Get the clipboard data ( ' Paste ' ) .
 Returns : Data ( string ) retrieved or None if empty . Exceptions from
 AppKit will be handled by caller ."""

implementation:
pb = AppKit . NSPasteboard . generalPasteboard ( )
# If we allow for multiple data types ( e . g . a list of data types )
# we will have to add a condition to check just the first in the
# list of datatypes )
data = pb . stringForType_ ( cls . STRING )
return data


signature:
def copy ( cls , data ) :
    """Set the clipboard data ( ' Copy ' ) .
 Parameters : data to set ( string )
 Optional : datatype if it ' s not a string
 Returns : True / False on successful copy , Any exception raised ( like
 passes the NSPasteboardCommunicationError ) should be caught
 by the caller ."""

implementation:
pp = pprint . PrettyPrinter ( )
copy_data = 'Data to copy (put in pasteboard): %s'
logging . debug ( copy_data % pp . pformat ( data ) )
# Clear the pasteboard first :
cleared = cls . clearAll ( )
if not cleared :
    logging . warning ( 'Clipboard could not clear properly' )
    return False
# Prepare to write the data
# If we just use writeObjects the sequence to write to the clipboard is
# a ) Call clearContents ( )
# b ) Call writeObjects ( ) with a list of objects to write to the
# clipboard
if not isinstance ( data , types . ListType ) :
    data = [ data ]
pb = AppKit . NSPasteboard . generalPasteboard ( )
pb_set_ok = pb . writeObjects_ ( data )
return bool ( pb_set_ok )


signature:
def clearContents ( cls ) :
    """Clear contents of general pasteboard .
 Future enhancement can include specifying which clipboard to clear
 Returns : True on success ; caller should expect to catch exceptions ,
 probably from AppKit ( ValueError )"""

implementation:
log_msg = 'Request to clear contents of pasteboard: general'
logging . debug ( log_msg )
pb = AppKit . NSPasteboard . generalPasteboard ( )
pb . clearContents ( )
return True


signature:
def isEmpty ( cls , datatype = None ) :
    """Method to test if the general pasteboard is empty or not with respect
 to the type of object you want .
 Parameters : datatype ( defaults to strings )
 Returns : Boolean True ( empty ) / False ( has contents ) ; Raises
 exception ( passes any raised up )"""

implementation:
if not datatype :
    datatype = AppKit . NSString
if not isinstance ( datatype , types . ListType ) :
    datatype = [ datatype ]
pp = pprint . PrettyPrinter ( )
logging . debug ( 'Desired datatypes: %s' % pp . pformat ( datatype ) )
opt_dict = { }
logging . debug ( 'Results filter is: %s' % pp . pformat ( opt_dict ) )
try :
    log_msg = 'Request to verify pasteboard is empty'
    logging . debug ( log_msg )
    pb = AppKit . NSPasteboard . generalPasteboard ( )
    # canReadObjectForClasses _ options _ ( ) seems to return an int ( > 0 if
    # True )
    # Need to negate to get the sense we want ( True if can not read the
    # data type from the pasteboard )
    its_empty = not bool ( pb . canReadObjectForClasses_options_ ( datatype , opt_dict ) )
except ValueError as error :
    logging . error ( error )
    raise
return bool ( its_empty )


signature:
def _ldtpize_accessible ( self , acc ) :
    """Get LDTP format accessibile name
 @ param acc : Accessible handle
 @ type acc : object
 @ return : object type , stripped object name ( associated / direct ) ,
 associated label
 @ rtype : tuple"""

implementation:
actual_role = self . _get_role ( acc )
label = self . _get_title ( acc )
if re . match ( "AXWindow" , actual_role , re . M | re . U | re . L ) : # Strip space and new line from window title
    strip = r"( |\n)"
else : # Strip space , colon , dot , underscore and new line from
# all other object types
    strip = r"( |:|\.|_|\n)"
if label : # Return the role type ( if , not in the know list of roles ,
# return ukn - unknown ) , strip the above characters from name
# also return labely _ by string
    label = re . sub ( strip , u"" , label )
role = abbreviated_roles . get ( actual_role , "ukn" )
if self . _ldtp_debug and role == "ukn" :
    print ( actual_role , acc )
return role , label


signature:
def _glob_match ( self , pattern , string ) :
    """Match given string , by escaping regex characters"""

implementation:
# regex flags Multi - line , Unicode , Locale
return bool ( re . match ( fnmatch . translate ( pattern ) , string , re . M | re . U | re . L ) )


signature:
def selectmenuitem ( self , window_name , object_name ) :
    """Select ( click ) a menu item .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
menu_handle = self . _get_menu_handle ( window_name , object_name )
if not menu_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
menu_handle . Press ( )
return 1


signature:
def doesmenuitemexist ( self , window_name , object_name ) :
    """Check a menu item exist .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ param strict _ hierarchy : Mandate menu hierarchy if set to True
 @ type object _ name : boolean
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    menu_handle = self . _get_menu_handle ( window_name , object_name , False )
    return 1
except LdtpServerException :
    return 0


signature:
def menuitemenabled ( self , window_name , object_name ) :
    """Verify a menu item is enabled
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    menu_handle = self . _get_menu_handle ( window_name , object_name , False )
    if menu_handle . AXEnabled :
        return 1
except LdtpServerException :
    pass
return 0


signature:
def listsubmenus ( self , window_name , object_name ) :
    """List children of menu item
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : menu item in list on success .
 @ rtype : list"""

implementation:
menu_handle = self . _get_menu_handle ( window_name , object_name )
role , label = self . _ldtpize_accessible ( menu_handle )
menu_clicked = False
try :
    if not menu_handle . AXChildren :
        menu_clicked = True
        try :
            menu_handle . Press ( )
            self . wait ( 1 )
        except atomac . _a11y . ErrorCannotComplete :
            pass
        if not menu_handle . AXChildren :
            raise LdtpServerException ( u"Unable to find children under menu %s" % label )
    children = menu_handle . AXChildren [ 0 ]
    sub_menus = [ ]
    for current_menu in children . AXChildren :
        role , label = self . _ldtpize_accessible ( current_menu )
        if not label : # All splitters have empty label
            continue
        sub_menus . append ( u"%s%s" % ( role , label ) )
finally :
    if menu_clicked :
        menu_handle . Cancel ( )
return sub_menus


signature:
def verifymenucheck ( self , window_name , object_name ) :
    """Verify a menu item is checked
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    menu_handle = self . _get_menu_handle ( window_name , object_name , False )
    try :
        if menu_handle . AXMenuItemMarkChar : # Checked
            return 1
    except atomac . _a11y . Error :
        pass
except LdtpServerException :
    pass
return 0


signature:
def menucheck ( self , window_name , object_name ) :
    """Check ( click ) a menu item .
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob . Or menu heirarchy
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
menu_handle = self . _get_menu_handle ( window_name , object_name )
if not menu_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
try :
    if menu_handle . AXMenuItemMarkChar : # Already checked
        return 1
except atomac . _a11y . Error :
    pass
menu_handle . Press ( )
return 1


signature:
def _getRunningApps ( cls ) :
    """Get a list of the running applications ."""

implementation:
def runLoopAndExit ( ) :
    AppHelper . stopEventLoop ( )
AppHelper . callLater ( 1 , runLoopAndExit )
AppHelper . runConsoleEventLoop ( )
# Get a list of running applications
ws = AppKit . NSWorkspace . sharedWorkspace ( )
apps = ws . runningApplications ( )
return apps


signature:
def getFrontmostApp ( cls ) :
    """Get the current frontmost application .
 Raise a ValueError exception if no GUI applications are found ."""

implementation:
# Refresh the runningApplications list
apps = cls . _getRunningApps ( )
for app in apps :
    pid = app . processIdentifier ( )
    ref = cls . getAppRefByPid ( pid )
    try :
        if ref . AXFrontmost :
            return ref
    except ( _a11y . ErrorUnsupported , _a11y . ErrorCannotComplete , _a11y . ErrorAPIDisabled , _a11y . ErrorNotImplemented ) : # Some applications do not have an explicit GUI
    # and so will not have an AXFrontmost attribute
    # Trying to read attributes from Google Chrome Helper returns
    # ErrorAPIDisabled for some reason - opened radar bug 12837995
        pass
raise ValueError ( 'No GUI application found.' )


signature:
def getAnyAppWithWindow ( cls ) :
    """Get a random app that has windows .
 Raise a ValueError exception if no GUI applications are found ."""

implementation:
# Refresh the runningApplications list
apps = cls . _getRunningApps ( )
for app in apps :
    pid = app . processIdentifier ( )
    ref = cls . getAppRefByPid ( pid )
    if hasattr ( ref , 'windows' ) and len ( ref . windows ( ) ) > 0 :
        return ref
raise ValueError ( 'No GUI application found.' )


signature:
def launchAppByBundleId ( bundleID ) :
    """Launch the application with the specified bundle ID"""

implementation:
# NSWorkspaceLaunchAllowingClassicStartup does nothing on any
# modern system that doesn ' t have the classic environment installed .
# Encountered a bug when passing 0 for no options on 10.6 PyObjC .
ws = AppKit . NSWorkspace . sharedWorkspace ( )
# Sorry about the length of the following line
r = ws . launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_ ( bundleID , AppKit . NSWorkspaceLaunchAllowingClassicStartup , AppKit . NSAppleEventDescriptor . nullDescriptor ( ) , None )
# On 10.6 , this returns a tuple - first element bool result , second is
# a number . Let ' s use the bool result .
if not r [ 0 ] :
    raise RuntimeError ( 'Error launching specified application.' )


signature:
def launchAppByBundlePath ( bundlePath , arguments = None ) :
    """Launch app with a given bundle path .
 Return True if succeed ."""

implementation:
if arguments is None :
    arguments = [ ]
bundleUrl = NSURL . fileURLWithPath_ ( bundlePath )
workspace = AppKit . NSWorkspace . sharedWorkspace ( )
arguments_strings = list ( map ( lambda a : NSString . stringWithString_ ( str ( a ) ) , arguments ) )
arguments = NSDictionary . dictionaryWithDictionary_ ( { AppKit . NSWorkspaceLaunchConfigurationArguments : NSArray . arrayWithArray_ ( arguments_strings ) } )
return workspace . launchApplicationAtURL_options_configuration_error_ ( bundleUrl , AppKit . NSWorkspaceLaunchAllowingClassicStartup , arguments , None )


signature:
def terminateAppByBundleId ( bundleID ) :
    """Terminate app with a given bundle ID .
 Requires 10.6.
 Return True if succeed ."""

implementation:
ra = AppKit . NSRunningApplication
if getattr ( ra , "runningApplicationsWithBundleIdentifier_" ) :
    appList = ra . runningApplicationsWithBundleIdentifier_ ( bundleID )
    if appList and len ( appList ) > 0 :
        app = appList [ 0 ]
        return app and app . terminate ( ) and True or False
return False


signature:
def _postQueuedEvents ( self , interval = 0.01 ) :
    """Private method to post queued events ( e . g . Quartz events ) .
 Each event in queue is a tuple ( event call , args to event call ) ."""

implementation:
while len ( self . eventList ) > 0 :
    ( nextEvent , args ) = self . eventList . popleft ( )
    nextEvent ( * args )
    time . sleep ( interval )


signature:
def _queueEvent ( self , event , args ) :
    """Private method to queue events to run .
 Each event in queue is a tuple ( event call , args to event call ) ."""

implementation:
if not hasattr ( self , 'eventList' ) :
    self . eventList = deque ( [ ( event , args ) ] )
    return
self . eventList . append ( ( event , args ) )


signature:
def _addKeyToQueue ( self , keychr , modFlags = 0 , globally = False ) :
    """Add keypress to queue .
 Parameters : key character or constant referring to a non - alpha - numeric
 key ( e . g . RETURN or TAB )
 modifiers
 global or app specific
 Returns : None or raise ValueError exception ."""

implementation:
# Awkward , but makes modifier - key - only combinations possible
# ( since sendKeyWithModifiers ( ) calls this )
if not keychr :
    return
if not hasattr ( self , 'keyboard' ) :
    self . keyboard = AXKeyboard . loadKeyboard ( )
if keychr in self . keyboard [ 'upperSymbols' ] and not modFlags :
    self . _sendKeyWithModifiers ( keychr , [ AXKeyCodeConstants . SHIFT ] , globally )
    return
if keychr . isupper ( ) and not modFlags :
    self . _sendKeyWithModifiers ( keychr . lower ( ) , [ AXKeyCodeConstants . SHIFT ] , globally )
    return
if keychr not in self . keyboard :
    self . _clearEventQueue ( )
    raise ValueError ( 'Key %s not found in keyboard layout' % keychr )
# Press the key
keyDown = Quartz . CGEventCreateKeyboardEvent ( None , self . keyboard [ keychr ] , True )
# Release the key
keyUp = Quartz . CGEventCreateKeyboardEvent ( None , self . keyboard [ keychr ] , False )
# Set modflags on keyDown ( default None ) :
Quartz . CGEventSetFlags ( keyDown , modFlags )
# Set modflags on keyUp :
Quartz . CGEventSetFlags ( keyUp , modFlags )
# Post the event to the given app
if not globally : # To direct output to the correct application need the PSN ( macOS < = 10.10 ) or PID ( macOS > 10.10 ) :
    macVer , _ , _ = platform . mac_ver ( )
    macVer = int ( macVer . split ( '.' ) [ 1 ] )
    if macVer > 10 :
        appPid = self . _getPid ( )
        self . _queueEvent ( Quartz . CGEventPostToPid , ( appPid , keyDown ) )
        self . _queueEvent ( Quartz . CGEventPostToPid , ( appPid , keyUp ) )
    else :
        appPsn = self . _getPsnForPid ( self . _getPid ( ) )
        self . _queueEvent ( Quartz . CGEventPostToPSN , ( appPsn , keyDown ) )
        self . _queueEvent ( Quartz . CGEventPostToPSN , ( appPsn , keyUp ) )
else :
    self . _queueEvent ( Quartz . CGEventPost , ( 0 , keyDown ) )
    self . _queueEvent ( Quartz . CGEventPost , ( 0 , keyUp ) )


signature:
def _sendKey ( self , keychr , modFlags = 0 , globally = False ) :
    """Send one character with no modifiers .
 Parameters : key character or constant referring to a non - alpha - numeric
 key ( e . g . RETURN or TAB )
 modifier flags ,
 global or app specific
 Returns : None or raise ValueError exception"""

implementation:
escapedChrs = { '\n' : AXKeyCodeConstants . RETURN , '\r' : AXKeyCodeConstants . RETURN , '\t' : AXKeyCodeConstants . TAB , }
if keychr in escapedChrs :
    keychr = escapedChrs [ keychr ]
self . _addKeyToQueue ( keychr , modFlags , globally = globally )
self . _postQueuedEvents ( )


signature:
def _pressModifiers ( self , modifiers , pressed = True , globally = False ) :
    """Press given modifiers ( provided in list form ) .
 Parameters : modifiers list , global or app specific
 Optional : keypressed state ( default is True ( down ) )
 Returns : Unsigned int representing flags to set"""

implementation:
if not isinstance ( modifiers , list ) :
    raise TypeError ( 'Please provide modifiers in list form' )
if not hasattr ( self , 'keyboard' ) :
    self . keyboard = AXKeyboard . loadKeyboard ( )
modFlags = 0
# Press given modifiers
for nextMod in modifiers :
    if nextMod not in self . keyboard :
        errStr = 'Key %s not found in keyboard layout'
        self . _clearEventQueue ( )
        raise ValueError ( errStr % self . keyboard [ nextMod ] )
    modEvent = Quartz . CGEventCreateKeyboardEvent ( Quartz . CGEventSourceCreate ( 0 ) , self . keyboard [ nextMod ] , pressed )
    if not pressed : # Clear the modflags :
        Quartz . CGEventSetFlags ( modEvent , 0 )
    if globally :
        self . _queueEvent ( Quartz . CGEventPost , ( 0 , modEvent ) )
    else : # To direct output to the correct application need the PSN ( macOS < = 10.10 ) or PID ( macOS > 10.10 ) :
        macVer , _ , _ = platform . mac_ver ( )
        macVer = int ( macVer . split ( '.' ) [ 1 ] )
        if macVer > 10 :
            appPid = self . _getPid ( )
            self . _queueEvent ( Quartz . CGEventPostToPid , ( appPid , modEvent ) )
        else :
            appPsn = self . _getPsnForPid ( self . _getPid ( ) )
            self . _queueEvent ( Quartz . CGEventPostToPSN , ( appPsn , modEvent ) )
    # Add the modifier flags
    modFlags += AXKeyboard . modKeyFlagConstants [ nextMod ]
return modFlags


signature:
def _holdModifierKeys ( self , modifiers ) :
    """Hold given modifier keys ( provided in list form ) .
 Parameters : modifiers list
 Returns : Unsigned int representing flags to set"""

implementation:
modFlags = self . _pressModifiers ( modifiers )
# Post the queued keypresses :
self . _postQueuedEvents ( )
return modFlags


signature:
def _releaseModifiers ( self , modifiers , globally = False ) :
    """Release given modifiers ( provided in list form ) .
 Parameters : modifiers list
 Returns : None"""

implementation:
# Release them in reverse order from pressing them :
modifiers . reverse ( )
modFlags = self . _pressModifiers ( modifiers , pressed = False , globally = globally )
return modFlags


signature:
def _releaseModifierKeys ( self , modifiers ) :
    """Release given modifier keys ( provided in list form ) .
 Parameters : modifiers list
 Returns : Unsigned int representing flags to set"""

implementation:
modFlags = self . _releaseModifiers ( modifiers )
# Post the queued keypresses :
self . _postQueuedEvents ( )
return modFlags


signature:
def _isSingleCharacter ( keychr ) :
    """Check whether given keyboard character is a single character .
 Parameters : key character which will be checked .
 Returns : True when given key character is a single character ."""

implementation:
if not keychr :
    return False
# Regular character case .
if len ( keychr ) == 1 :
    return True
# Tagged character case .
return keychr . count ( '<' ) == 1 and keychr . count ( '>' ) == 1 and keychr [ 0 ] == '<' and keychr [ - 1 ] == '>'


signature:
def _sendKeyWithModifiers ( self , keychr , modifiers , globally = False ) :
    """Send one character with the given modifiers pressed .
 Parameters : key character , list of modifiers , global or app specific
 Returns : None or raise ValueError exception"""

implementation:
if not self . _isSingleCharacter ( keychr ) :
    raise ValueError ( 'Please provide only one character to send' )
if not hasattr ( self , 'keyboard' ) :
    self . keyboard = AXKeyboard . loadKeyboard ( )
modFlags = self . _pressModifiers ( modifiers , globally = globally )
# Press the non - modifier key
self . _sendKey ( keychr , modFlags , globally = globally )
# Release the modifiers
self . _releaseModifiers ( modifiers , globally = globally )
# Post the queued keypresses :
self . _postQueuedEvents ( )


signature:
def _queueMouseButton ( self , coord , mouseButton , modFlags , clickCount = 1 , dest_coord = None ) :
    """Private method to handle generic mouse button clicking .
 Parameters : coord ( x , y ) to click , mouseButton ( e . g . ,
 kCGMouseButtonLeft ) , modFlags set ( int )
 Optional : clickCount ( default 1 ; set to 2 for double - click ; 3 for
 triple - click on host )
 Returns : None"""

implementation:
# For now allow only left and right mouse buttons :
mouseButtons = { Quartz . kCGMouseButtonLeft : 'LeftMouse' , Quartz . kCGMouseButtonRight : 'RightMouse' , }
if mouseButton not in mouseButtons :
    raise ValueError ( 'Mouse button given not recognized' )
eventButtonDown = getattr ( Quartz , 'kCGEvent%sDown' % mouseButtons [ mouseButton ] )
eventButtonUp = getattr ( Quartz , 'kCGEvent%sUp' % mouseButtons [ mouseButton ] )
eventButtonDragged = getattr ( Quartz , 'kCGEvent%sDragged' % mouseButtons [ mouseButton ] )
# Press the button
buttonDown = Quartz . CGEventCreateMouseEvent ( None , eventButtonDown , coord , mouseButton )
# Set modflags ( default None ) on button down :
Quartz . CGEventSetFlags ( buttonDown , modFlags )
# Set the click count on button down :
Quartz . CGEventSetIntegerValueField ( buttonDown , Quartz . kCGMouseEventClickState , int ( clickCount ) )
if dest_coord : # Drag and release the button
    buttonDragged = Quartz . CGEventCreateMouseEvent ( None , eventButtonDragged , dest_coord , mouseButton )
    # Set modflags on the button dragged :
    Quartz . CGEventSetFlags ( buttonDragged , modFlags )
    buttonUp = Quartz . CGEventCreateMouseEvent ( None , eventButtonUp , dest_coord , mouseButton )
else : # Release the button
    buttonUp = Quartz . CGEventCreateMouseEvent ( None , eventButtonUp , coord , mouseButton )
# Set modflags on the button up :
Quartz . CGEventSetFlags ( buttonUp , modFlags )
# Set the click count on button up :
Quartz . CGEventSetIntegerValueField ( buttonUp , Quartz . kCGMouseEventClickState , int ( clickCount ) )
# Queue the events
self . _queueEvent ( Quartz . CGEventPost , ( Quartz . kCGSessionEventTap , buttonDown ) )
if dest_coord :
    self . _queueEvent ( Quartz . CGEventPost , ( Quartz . kCGHIDEventTap , buttonDragged ) )
self . _queueEvent ( Quartz . CGEventPost , ( Quartz . kCGSessionEventTap , buttonUp ) )


signature:
def _leftMouseDragged ( self , stopCoord , strCoord , speed ) :
    """Private method to handle generic mouse left button dragging and
 dropping .
 Parameters : stopCoord ( x , y ) drop point
 Optional : strCoord ( x , y ) drag point , default ( 0,0 ) get current
 mouse position
 speed ( int ) 1 to unlimit , simulate mouse moving
 action from some special requirement
 Returns : None"""

implementation:
# To direct output to the correct application need the PSN :
appPid = self . _getPid ( )
# Get current position as start point if strCoord not given
if strCoord == ( 0 , 0 ) :
    loc = AppKit . NSEvent . mouseLocation ( )
    strCoord = ( loc . x , Quartz . CGDisplayPixelsHigh ( 0 ) - loc . y )
# To direct output to the correct application need the PSN :
appPid = self . _getPid ( )
# Press left button down
pressLeftButton = Quartz . CGEventCreateMouseEvent ( None , Quartz . kCGEventLeftMouseDown , strCoord , Quartz . kCGMouseButtonLeft )
# Queue the events
Quartz . CGEventPost ( Quartz . CoreGraphics . kCGHIDEventTap , pressLeftButton )
# Wait for reponse of system , a fuzzy icon appears
time . sleep ( 5 )
# Simulate mouse moving speed , k is slope
speed = round ( 1 / float ( speed ) , 2 )
xmoved = stopCoord [ 0 ] - strCoord [ 0 ]
ymoved = stopCoord [ 1 ] - strCoord [ 1 ]
if ymoved == 0 :
    raise ValueError ( 'Not support horizontal moving' )
else :
    k = abs ( ymoved / xmoved )
if xmoved != 0 :
    for xpos in range ( int ( abs ( xmoved ) ) ) :
        if xmoved > 0 and ymoved > 0 :
            currcoord = ( strCoord [ 0 ] + xpos , strCoord [ 1 ] + xpos * k )
        elif xmoved > 0 and ymoved < 0 :
            currcoord = ( strCoord [ 0 ] + xpos , strCoord [ 1 ] - xpos * k )
        elif xmoved < 0 and ymoved < 0 :
            currcoord = ( strCoord [ 0 ] - xpos , strCoord [ 1 ] - xpos * k )
        elif xmoved < 0 and ymoved > 0 :
            currcoord = ( strCoord [ 0 ] - xpos , strCoord [ 1 ] + xpos * k )
        # Drag with left button
        dragLeftButton = Quartz . CGEventCreateMouseEvent ( None , Quartz . kCGEventLeftMouseDragged , currcoord , Quartz . kCGMouseButtonLeft )
        Quartz . CGEventPost ( Quartz . CoreGraphics . kCGHIDEventTap , dragLeftButton )
        # Wait for reponse of system
        time . sleep ( speed )
else :
    raise ValueError ( 'Not support vertical moving' )
upLeftButton = Quartz . CGEventCreateMouseEvent ( None , Quartz . kCGEventLeftMouseUp , stopCoord , Quartz . kCGMouseButtonLeft )
# Wait for reponse of system , a plus icon appears
time . sleep ( 5 )
# Up left button up
Quartz . CGEventPost ( Quartz . CoreGraphics . kCGHIDEventTap , upLeftButton )


signature:
def _waitFor ( self , timeout , notification , ** kwargs ) :
    """Wait for a particular UI event to occur ; this can be built
 upon in NativeUIElement for specific convenience methods ."""

implementation:
callback = self . _matchOther
retelem = None
callbackArgs = None
callbackKwargs = None
# Allow customization of the callback , though by default use the basic
# _ match ( ) method
if 'callback' in kwargs :
    callback = kwargs [ 'callback' ]
    del kwargs [ 'callback' ]
    # Deal with these only if callback is provided :
    if 'args' in kwargs :
        if not isinstance ( kwargs [ 'args' ] , tuple ) :
            errStr = 'Notification callback args not given as a tuple'
            raise TypeError ( errStr )
        # If args are given , notification will pass back the returned
        # element in the first positional arg
        callbackArgs = kwargs [ 'args' ]
        del kwargs [ 'args' ]
    if 'kwargs' in kwargs :
        if not isinstance ( kwargs [ 'kwargs' ] , dict ) :
            errStr = 'Notification callback kwargs not given as a dict'
            raise TypeError ( errStr )
        callbackKwargs = kwargs [ 'kwargs' ]
        del kwargs [ 'kwargs' ]
    # If kwargs are not given as a dictionary but individually listed
    # need to update the callbackKwargs dict with the remaining items in
    # kwargs
    if kwargs :
        if callbackKwargs :
            callbackKwargs . update ( kwargs )
        else :
            callbackKwargs = kwargs
else :
    callbackArgs = ( retelem , )
    # Pass the kwargs to the default callback
    callbackKwargs = kwargs
return self . _setNotification ( timeout , notification , callback , callbackArgs , callbackKwargs )


signature:
def waitForFocusToMatchCriteria ( self , timeout = 10 , ** kwargs ) :
    """Convenience method to wait for focused element to change
 ( to element matching kwargs criteria ) .
 Returns : Element or None"""

implementation:
def _matchFocused ( retelem , ** kwargs ) :
    return retelem if retelem . _match ( ** kwargs ) else None
retelem = None
return self . _waitFor ( timeout , 'AXFocusedUIElementChanged' , callback = _matchFocused , args = ( retelem , ) , ** kwargs )


signature:
def _getActions ( self ) :
    """Retrieve a list of actions supported by the object ."""

implementation:
actions = _a11y . AXUIElement . _getActions ( self )
# strip leading AX from actions - help distinguish them from attributes
return [ action [ 2 : ] for action in actions ]


signature:
def _performAction ( self , action ) :
    """Perform the specified action ."""

implementation:
try :
    _a11y . AXUIElement . _performAction ( self , 'AX%s' % action )
except _a11y . ErrorUnsupported as e :
    sierra_ver = '10.12'
    if mac_ver ( ) [ 0 ] < sierra_ver :
        raise e
    else :
        pass


signature:
def _generateChildren ( self ) :
    """Generator which yields all AXChildren of the object ."""

implementation:
try :
    children = self . AXChildren
except _a11y . Error :
    return
if children :
    for child in children :
        yield child


signature:
def _generateChildrenR ( self , target = None ) :
    """Generator which recursively yields all AXChildren of the object ."""

implementation:
if target is None :
    target = self
try :
    children = target . AXChildren
except _a11y . Error :
    return
if children :
    for child in children :
        yield child
        for c in self . _generateChildrenR ( child ) :
            yield c


signature:
def _match ( self , ** kwargs ) :
    """Method which indicates if the object matches specified criteria .
 Match accepts criteria as kwargs and looks them up on attributes .
 Actual matching is performed with fnmatch , so shell - like wildcards
 work within match strings . Examples :
 obj . _ match ( AXTitle = ' Terminal * ' )
 obj . _ match ( AXRole = ' TextField ' , AXRoleDescription = ' search text field ' )"""

implementation:
for k in kwargs . keys ( ) :
    try :
        val = getattr ( self , k )
    except _a11y . Error :
        return False
    # Not all values may be strings ( e . g . size , position )
    if sys . version_info [ : 2 ] <= ( 2 , 6 ) :
        if isinstance ( val , basestring ) :
            if not fnmatch . fnmatch ( unicode ( val ) , kwargs [ k ] ) :
                return False
        else :
            if val != kwargs [ k ] :
                return False
    elif sys . version_info [ 0 ] == 3 :
        if isinstance ( val , str ) :
            if not fnmatch . fnmatch ( val , str ( kwargs [ k ] ) ) :
                return False
        else :
            if val != kwargs [ k ] :
                return False
    else :
        if isinstance ( val , str ) or isinstance ( val , unicode ) :
            if not fnmatch . fnmatch ( val , kwargs [ k ] ) :
                return False
        else :
            if val != kwargs [ k ] :
                return False
return True


signature:
def _matchOther ( self , obj , ** kwargs ) :
    """Perform _ match but on another object , not self ."""

implementation:
if obj is not None : # Need to check that the returned UI element wasn ' t destroyed first :
    if self . _findFirstR ( ** kwargs ) :
        return obj . _match ( ** kwargs )
return False


signature:
def _generateFind ( self , ** kwargs ) :
    """Generator which yields matches on AXChildren ."""

implementation:
for needle in self . _generateChildren ( ) :
    if needle . _match ( ** kwargs ) :
        yield needle


signature:
def _generateFindR ( self , ** kwargs ) :
    """Generator which yields matches on AXChildren and their children ."""

implementation:
for needle in self . _generateChildrenR ( ) :
    if needle . _match ( ** kwargs ) :
        yield needle


signature:
def _findAll ( self , ** kwargs ) :
    """Return a list of all children that match the specified criteria ."""

implementation:
result = [ ]
for item in self . _generateFind ( ** kwargs ) :
    result . append ( item )
return result


signature:
def _findAllR ( self , ** kwargs ) :
    """Return a list of all children ( recursively ) that match the specified
 criteria ."""

implementation:
result = [ ]
for item in self . _generateFindR ( ** kwargs ) :
    result . append ( item )
return result


signature:
def _getApplication ( self ) :
    """Get the base application UIElement .
 If the UIElement is a child of the application , it will try
 to get the AXParent until it reaches the top application level
 element ."""

implementation:
app = self
while True :
    try :
        app = app . AXParent
    except _a11y . ErrorUnsupported :
        break
return app


signature:
def _menuItem ( self , menuitem , * args ) :
    """Return the specified menu item .
 Example - refer to items by name :
 app . _ menuItem ( app . AXMenuBar , ' File ' , ' New ' ) . Press ( )
 app . _ menuItem ( app . AXMenuBar , ' Edit ' , ' Insert ' , ' Line Break ' ) . Press ( )
 Refer to items by index :
 app . _ menuitem ( app . AXMenuBar , 1 , 0 ) . Press ( )
 Refer to items by mix - n - match :
 app . _ menuitem ( app . AXMenuBar , 1 , ' About TextEdit ' ) . Press ( )"""

implementation:
self . _activate ( )
for item in args : # If the item has an AXMenu as a child , navigate into it .
# This seems like a silly abstraction added by apple ' s a11y api .
    if menuitem . AXChildren [ 0 ] . AXRole == 'AXMenu' :
        menuitem = menuitem . AXChildren [ 0 ]
    # Find AXMenuBarItems and AXMenuItems using a handy wildcard
    role = 'AXMenu*Item'
    try :
        menuitem = menuitem . AXChildren [ int ( item ) ]
    except ValueError :
        menuitem = menuitem . findFirst ( AXRole = 'AXMenu*Item' , AXTitle = item )
return menuitem


signature:
def _activate ( self ) :
    """Activate the application ( bringing menus and windows forward ) ."""

implementation:
ra = AppKit . NSRunningApplication
app = ra . runningApplicationWithProcessIdentifier_ ( self . _getPid ( ) )
# NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps
# = = 3 - PyObjC in 10.6 does not expose these constants though so I have
# to use the int instead of the symbolic names
app . activateWithOptions_ ( 3 )


signature:
def _getBundleId ( self ) :
    """Return the bundle ID of the application ."""

implementation:
ra = AppKit . NSRunningApplication
app = ra . runningApplicationWithProcessIdentifier_ ( self . _getPid ( ) )
return app . bundleIdentifier ( )


signature:
def menuItem ( self , * args ) :
    """Return the specified menu item .
 Example - refer to items by name :
 app . menuItem ( ' File ' , ' New ' ) . Press ( )
 app . menuItem ( ' Edit ' , ' Insert ' , ' Line Break ' ) . Press ( )
 Refer to items by index :
 app . menuitem ( 1 , 0 ) . Press ( )
 Refer to items by mix - n - match :
 app . menuitem ( 1 , ' About TextEdit ' ) . Press ( )"""

implementation:
menuitem = self . _getApplication ( ) . AXMenuBar
return self . _menuItem ( menuitem , * args )


signature:
def popUpItem ( self , * args ) :
    """Return the specified item in a pop up menu ."""

implementation:
self . Press ( )
time . sleep ( .5 )
return self . _menuItem ( self , * args )


signature:
def dragMouseButtonLeft ( self , coord , dest_coord , interval = 0.5 ) :
    """Drag the left mouse button without modifiers pressed .
 Parameters : coordinates to click on screen ( tuple ( x , y ) )
 dest coordinates to drag to ( tuple ( x , y ) )
 interval to send event of btn down , drag and up
 Returns : None"""

implementation:
modFlags = 0
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , dest_coord = dest_coord )
self . _postQueuedEvents ( interval = interval )


signature:
def doubleClickDragMouseButtonLeft ( self , coord , dest_coord , interval = 0.5 ) :
    """Double - click and drag the left mouse button without modifiers
 pressed .
 Parameters : coordinates to double - click on screen ( tuple ( x , y ) )
 dest coordinates to drag to ( tuple ( x , y ) )
 interval to send event of btn down , drag and up
 Returns : None"""

implementation:
modFlags = 0
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , dest_coord = dest_coord )
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , dest_coord = dest_coord , clickCount = 2 )
self . _postQueuedEvents ( interval = interval )


signature:
def clickMouseButtonLeft ( self , coord , interval = None ) :
    """Click the left mouse button without modifiers pressed .
 Parameters : coordinates to click on screen ( tuple ( x , y ) )
 Returns : None"""

implementation:
modFlags = 0
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags )
if interval :
    self . _postQueuedEvents ( interval = interval )
else :
    self . _postQueuedEvents ( )


signature:
def clickMouseButtonRight ( self , coord ) :
    """Click the right mouse button without modifiers pressed .
 Parameters : coordinates to click on scren ( tuple ( x , y ) )
 Returns : None"""

implementation:
modFlags = 0
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonRight , modFlags )
self . _postQueuedEvents ( )


signature:
def clickMouseButtonLeftWithMods ( self , coord , modifiers , interval = None ) :
    """Click the left mouse button with modifiers pressed .
 Parameters : coordinates to click ; modifiers ( list ) ( e . g . [ SHIFT ] or
 [ COMMAND , SHIFT ] ( assuming you ' ve first used
 from pyatom . AXKeyCodeConstants import * ) )
 Returns : None"""

implementation:
modFlags = self . _pressModifiers ( modifiers )
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags )
self . _releaseModifiers ( modifiers )
if interval :
    self . _postQueuedEvents ( interval = interval )
else :
    self . _postQueuedEvents ( )


signature:
def clickMouseButtonRightWithMods ( self , coord , modifiers ) :
    """Click the right mouse button with modifiers pressed .
 Parameters : coordinates to click ; modifiers ( list )
 Returns : None"""

implementation:
modFlags = self . _pressModifiers ( modifiers )
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonRight , modFlags )
self . _releaseModifiers ( modifiers )
self . _postQueuedEvents ( )


signature:
def leftMouseDragged ( self , stopCoord , strCoord = ( 0 , 0 ) , speed = 1 ) :
    """Click the left mouse button and drag object .
 Parameters : stopCoord , the position of dragging stopped
 strCoord , the position of dragging started
 (0,0 ) will get current position
 speed is mouse moving speed , 0 to unlimited
 Returns : None"""

implementation: self . _leftMouseDragged ( stopCoord , strCoord , speed )


signature:
def doubleClickMouse ( self , coord ) :
    """Double - click primary mouse button .
 Parameters : coordinates to click ( assume primary is left button )
 Returns : None"""

implementation:
modFlags = 0
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags )
# This is a kludge :
# If directed towards a Fusion VM the clickCount gets ignored and this
# will be seen as a single click , so in sequence this will be a double -
# click
# Otherwise to a host app only this second one will count as a double -
# click
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , clickCount = 2 )
self . _postQueuedEvents ( )


signature:
def doubleMouseButtonLeftWithMods ( self , coord , modifiers ) :
    """Click the left mouse button with modifiers pressed .
 Parameters : coordinates to click ; modifiers ( list )
 Returns : None"""

implementation:
modFlags = self . _pressModifiers ( modifiers )
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags )
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , clickCount = 2 )
self . _releaseModifiers ( modifiers )
self . _postQueuedEvents ( )


signature:
def tripleClickMouse ( self , coord ) :
    """Triple - click primary mouse button .
 Parameters : coordinates to click ( assume primary is left button )
 Returns : None"""

implementation:
# Note above re : double - clicks applies to triple - clicks
modFlags = 0
for i in range ( 2 ) :
    self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags )
self . _queueMouseButton ( coord , Quartz . kCGMouseButtonLeft , modFlags , clickCount = 3 )
self . _postQueuedEvents ( )


signature:
def waitFor ( self , timeout , notification , ** kwargs ) :
    """Generic wait for a UI event that matches the specified
 criteria to occur .
 For customization of the callback , use keyword args labeled
 ' callback ' , ' args ' , and ' kwargs ' for the callback fn , callback args ,
 and callback kwargs , respectively . Also note that on return ,
 the observer - returned UI element will be included in the first
 argument if ' args ' are given . Note also that if the UI element is
 destroyed , callback should not use it , otherwise the function will
 hang ."""

implementation: return self . _waitFor ( timeout , notification , ** kwargs )


signature:
def waitForCreation ( self , timeout = 10 , notification = 'AXCreated' ) :
    """Convenience method to wait for creation of some UI element .
 Returns : The element created"""

implementation:
callback = AXCallbacks . returnElemCallback
retelem = None
args = ( retelem , )
return self . waitFor ( timeout , notification , callback = callback , args = args )


signature:
def waitForWindowToDisappear ( self , winName , timeout = 10 ) :
    """Convenience method to wait for a window with the given name to
 disappear .
 Returns : Boolean"""

implementation:
callback = AXCallbacks . elemDisappearedCallback
retelem = None
args = ( retelem , self )
# For some reason for the AXUIElementDestroyed notification to fire ,
# we need to have a reference to it first
win = self . findFirst ( AXRole = 'AXWindow' , AXTitle = winName )
return self . waitFor ( timeout , 'AXUIElementDestroyed' , callback = callback , args = args , AXRole = 'AXWindow' , AXTitle = winName )


signature:
def waitForValueToChange ( self , timeout = 10 ) :
    """Convenience method to wait for value attribute of given element to
 change .
 Some types of elements ( e . g . menu items ) have their titles change ,
 so this will not work for those . This seems to work best if you set
 the notification at the application level .
 Returns : Element or None"""

implementation:
# Want to identify that the element whose value changes matches this
# object ' s . Unique identifiers considered include role and position
# This seems to work best if you set the notification at the application
# level
callback = AXCallbacks . returnElemCallback
retelem = None
return self . waitFor ( timeout , 'AXValueChanged' , callback = callback , args = ( retelem , ) )


signature:
def waitForFocusToChange ( self , newFocusedElem , timeout = 10 ) :
    """Convenience method to wait for focused element to change ( to new
 element given ) .
 Returns : Boolean"""

implementation: return self . waitFor ( timeout , 'AXFocusedUIElementChanged' , AXRole = newFocusedElem . AXRole , AXPosition = newFocusedElem . AXPosition )


signature:
def waitForFocusedWindowToChange ( self , nextWinName , timeout = 10 ) :
    """Convenience method to wait for focused window to change
 Returns : Boolean"""

implementation:
callback = AXCallbacks . returnElemCallback
retelem = None
return self . waitFor ( timeout , 'AXFocusedWindowChanged' , AXTitle = nextWinName )


signature:
def _convenienceMatch ( self , role , attr , match ) :
    """Method used by role based convenience functions to find a match"""

implementation:
kwargs = { }
# If the user supplied some text to search for ,
# supply that in the kwargs
if match :
    kwargs [ attr ] = match
return self . findAll ( AXRole = role , ** kwargs )


signature:
def _convenienceMatchR ( self , role , attr , match ) :
    """Method used by role based convenience functions to find a match"""

implementation:
kwargs = { }
# If the user supplied some text to search for ,
# supply that in the kwargs
if match :
    kwargs [ attr ] = match
return self . findAllR ( AXRole = role , ** kwargs )


signature:
def imagecapture ( self , window_name = None , x = 0 , y = 0 , width = None , height = None ) :
    """Captures screenshot of the whole desktop or given window
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param x : x co - ordinate value
 @ type x : int
 @ param y : y co - ordinate value
 @ type y : int
 @ param width : width co - ordinate value
 @ type width : int
 @ param height : height co - ordinate value
 @ type height : int
 @ return : screenshot with base64 encoded for the client
 @ rtype : string"""

implementation:
if x or y or ( width and width != - 1 ) or ( height and height != - 1 ) :
    raise LdtpServerException ( "Not implemented" )
if window_name :
    handle , name , app = self . _get_window_handle ( window_name )
    try :
        self . _grabfocus ( handle )
    except :
        pass
    rect = self . _getobjectsize ( handle )
    screenshot = CGWindowListCreateImage ( NSMakeRect ( rect [ 0 ] , rect [ 1 ] , rect [ 2 ] , rect [ 3 ] ) , 1 , 0 , 0 )
else :
    screenshot = CGWindowListCreateImage ( CGRectInfinite , 1 , 0 , 0 )
image = CIImage . imageWithCGImage_ ( screenshot )
bitmapRep = NSBitmapImageRep . alloc ( ) . initWithCIImage_ ( image )
blob = bitmapRep . representationUsingType_properties_ ( NSPNGFileType , None )
tmpFile = tempfile . mktemp ( '.png' , 'ldtpd_' )
blob . writeToFile_atomically_ ( tmpFile , False )
rv = b64encode ( open ( tmpFile ) . read ( ) )
os . remove ( tmpFile )
return rv


signature:
def startlog ( filename , overwrite = True ) :
    """@ param filename : Start logging on the specified file
 @ type filename : string
 @ param overwrite : Overwrite or append
 False - Append log to an existing file
 True - Write log to a new file . If file already exist ,
 then erase existing file content and start log
 @ type overwrite : boolean
 @ return : 1 on success and 0 on error
 @ rtype : integer"""

implementation:
if not filename :
    return 0
if overwrite : # Create new file , by overwriting existing file
    _mode = 'w'
else : # Append existing file
    _mode = 'a'
global _file_logger
# Create logging file handler
_file_logger = logging . FileHandler ( os . path . expanduser ( filename ) , _mode )
# Log ' Levelname : Messages ' , eg : ' ERROR : Logged message '
_formatter = logging . Formatter ( '%(levelname)-8s: %(message)s' )
_file_logger . setFormatter ( _formatter )
logger . addHandler ( _file_logger )
if _ldtp_debug : # On debug , change the default log level to DEBUG
    _file_logger . setLevel ( logging . DEBUG )
else : # else log in case of ERROR level and above
    _file_logger . setLevel ( logging . ERROR )
return 1


signature:
def removecallback ( window_name ) :
    """Remove registered callback on window create
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ return : 1 if registration was successful , 0 if not .
 @ rtype : integer"""

implementation:
if window_name in _pollEvents . _callback :
    del _pollEvents . _callback [ window_name ]
return _remote_removecallback ( window_name )


signature:
def callAfter ( func , * args , ** kwargs ) :
    """call a function on the main thread ( async )"""

implementation:
pool = NSAutoreleasePool . alloc ( ) . init ( )
obj = PyObjCAppHelperCaller_wrap . alloc ( ) . initWithArgs_ ( ( func , args , kwargs ) )
obj . callAfter_ ( None )
del obj
del pool


signature:
def callLater ( delay , func , * args , ** kwargs ) :
    """call a function on the main thread after a delay ( async )"""

implementation:
pool = NSAutoreleasePool . alloc ( ) . init ( )
obj = PyObjCAppHelperCaller_wrap . alloc ( ) . initWithArgs_ ( ( func , args , kwargs ) )
obj . callLater_ ( delay )
del obj
del pool


signature:
def stopEventLoop ( ) :
    """Stop the current event loop if possible
 returns True if it expects that it was successful , False otherwise"""

implementation:
stopper = PyObjCAppHelperRunLoopStopper_wrap . currentRunLoopStopper ( )
if stopper is None :
    if NSApp ( ) is not None :
        NSApp ( ) . terminate_ ( None )
        return True
    return False
NSTimer . scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_ ( 0.0 , stopper , 'performStop:' , None , False )
return True


signature:
def runEventLoop ( argv = None , unexpectedErrorAlert = None , installInterrupt = None , pdb = None , main = NSApplicationMain ) :
    """Run the event loop , ask the user if we should continue if an
 exception is caught . Use this function instead of NSApplicationMain ( ) ."""

implementation:
if argv is None :
    argv = sys . argv
if pdb is None :
    pdb = 'USE_PDB' in os . environ
if pdb :
    from PyObjCTools import Debugging
    Debugging . installVerboseExceptionHandler ( )
    # bring it to the front , starting from terminal
    # often won ' t
    activator = PyObjCAppHelperApplicationActivator_wrap . alloc ( ) . init ( )
    NSNotificationCenter . defaultCenter ( ) . addObserver_selector_name_object_ ( activator , 'activateNow:' , NSApplicationDidFinishLaunchingNotification , None , )
else :
    Debugging = None
if installInterrupt is None and pdb :
    installInterrupt = True
if unexpectedErrorAlert is None :
    unexpectedErrorAlert = unexpectedErrorAlertPdb
runLoop = NSRunLoop . currentRunLoop ( )
stopper = PyObjCAppHelperRunLoopStopper_wrap . alloc ( ) . init ( )
PyObjCAppHelperRunLoopStopper_wrap . addRunLoopStopper_toRunLoop_ ( stopper , runLoop )
firstRun = NSApp ( ) is None
try :
    while stopper . shouldRun ( ) :
        try :
            if firstRun :
                firstRun = False
                if installInterrupt :
                    installMachInterrupt ( )
                main ( argv )
            else :
                NSApp ( ) . run ( )
        except RAISETHESE :
            traceback . print_exc ( )
            break
        except :
            exctype , e , tb = sys . exc_info ( )
            objc_exception = False
            if isinstance ( e , objc . error ) :
                NSLog ( "%@" , str ( e ) )
            elif not unexpectedErrorAlert ( ) :
                NSLog ( "%@" , "An exception has occured:" )
                traceback . print_exc ( )
                sys . exit ( 0 )
            else :
                NSLog ( "%@" , "An exception has occured:" )
                traceback . print_exc ( )
        else :
            break
finally :
    if Debugging is not None :
        Debugging . removeExceptionHandler ( )
    PyObjCAppHelperRunLoopStopper_wrap . removeRunLoopStopperFromRunLoop_ ( runLoop )


signature:
def keypress ( self , data ) :
    """Press key . NOTE : keyrelease should be called
 @ param data : data to type .
 @ type data : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    window = self . _get_front_most_window ( )
except ( IndexError , ) :
    window = self . _get_any_window ( )
key_press_action = KeyPressAction ( window , data )
return 1


signature:
def keyrelease ( self , data ) :
    """Release key . NOTE : keypress should be called before this
 @ param data : data to type .
 @ type data : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    window = self . _get_front_most_window ( )
except ( IndexError , ) :
    window = self . _get_any_window ( )
key_release_action = KeyReleaseAction ( window , data )
return 1


signature:
def enterstring ( self , window_name , object_name = '' , data = '' ) :
    """Type string sequence .
 @ param window _ name : Window name to focus on , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to focus on , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param data : data to type .
 @ type data : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
if not object_name and not data :
    return self . generatekeyevent ( window_name )
else :
    object_handle = self . _get_object_handle ( window_name , object_name )
    if not object_handle . AXEnabled :
        raise LdtpServerException ( u"Object %s state disabled" % object_name )
    self . _grabfocus ( object_handle )
    object_handle . sendKeys ( data )
    return 1


signature:
def gettextvalue ( self , window_name , object_name , startPosition = 0 , endPosition = 0 ) :
    """Get text value
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param startPosition : Starting position of text to fetch
 @ type : startPosition : int
 @ param endPosition : Ending position of text to fetch
 @ type : endPosition : int
 @ return : text on success .
 @ rtype : string"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
return object_handle . AXValue


signature:
def inserttext ( self , window_name , object_name , position , data ) :
    """Insert string sequence in given position .
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param position : position where text has to be entered .
 @ type data : int
 @ param data : data to type .
 @ type data : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
existing_data = object_handle . AXValue
size = len ( existing_data )
if position < 0 :
    position = 0
if position > size :
    position = size
object_handle . AXValue = existing_data [ : position ] + data + existing_data [ position : ]
return 1


signature:
def verifypartialmatch ( self , window_name , object_name , partial_text ) :
    """Verify partial text
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param partial _ text : Partial text to match
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    if re . search ( fnmatch . translate ( partial_text ) , self . gettextvalue ( window_name , object_name ) ) :
        return 1
except :
    pass
return 0


signature:
def verifysettext ( self , window_name , object_name , text ) :
    """Verify text is set correctly
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param text : text to match
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    return int ( re . match ( fnmatch . translate ( text ) , self . gettextvalue ( window_name , object_name ) ) )
except :
    return 0


signature:
def istextstateenabled ( self , window_name , object_name ) :
    """Verifies text state enabled or not
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success 0 on failure .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name )
    if object_handle . AXEnabled :
        return 1
except LdtpServerException :
    pass
return 0


signature:
def getcharcount ( self , window_name , object_name ) :
    """Get character count
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
return object_handle . AXNumberOfCharacters


signature:
def appendtext ( self , window_name , object_name , data ) :
    """Append string sequence .
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param data : data to type .
 @ type data : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
object_handle . AXValue += data
return 1


signature:
def getcursorposition ( self , window_name , object_name ) :
    """Get cursor position
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : Cursor position on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
return object_handle . AXSelectedTextRange . loc


signature:
def setcursorposition ( self , window_name , object_name , cursor_position ) :
    """Set cursor position
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param cursor _ position : Cursor position to be set
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
object_handle . AXSelectedTextRange . loc = cursor_position
return 1


signature:
def cuttext ( self , window_name , object_name , start_position , end_position = - 1 ) :
    """cut text from start position to end position
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param start _ position : Start position
 @ type object _ name : integer
 @ param end _ position : End position , default - 1
 Cut all the text from start position till end
 @ type object _ name : integer
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
size = object_handle . AXNumberOfCharacters
if end_position == - 1 or end_position > size :
    end_position = size
if start_position < 0 :
    start_position = 0
data = object_handle . AXValue
Clipboard . copy ( data [ start_position : end_position ] )
object_handle . AXValue = data [ : start_position ] + data [ end_position : ]
return 1


signature:
def deletetext ( self , window_name , object_name , start_position , end_position = - 1 ) :
    """delete text from start position to end position
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param start _ position : Start position
 @ type object _ name : integer
 @ param end _ position : End position , default - 1
 Delete all the text from start position till end
 @ type object _ name : integer
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
size = object_handle . AXNumberOfCharacters
if end_position == - 1 or end_position > size :
    end_position = size
if start_position < 0 :
    start_position = 0
data = object_handle . AXValue
object_handle . AXValue = data [ : start_position ] + data [ end_position : ]
return 1


signature:
def pastetext ( self , window_name , object_name , position = 0 ) :
    """paste text from start position to end position
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ param position : Position to paste the text , default 0
 @ type object _ name : integer
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
if not object_handle . AXEnabled :
    raise LdtpServerException ( u"Object %s state disabled" % object_name )
size = object_handle . AXNumberOfCharacters
if position > size :
    position = size
if position < 0 :
    position = 0
clipboard = Clipboard . paste ( )
data = object_handle . AXValue
object_handle . AXValue = data [ : position ] + clipboard + data [ position : ]
return 1


signature:
def main ( port = 4118 , parentpid = None ) :
    """Main entry point . Parse command line options and start up a server ."""

implementation:
if "LDTP_DEBUG" in os . environ :
    _ldtp_debug = True
else :
    _ldtp_debug = False
_ldtp_debug_file = os . environ . get ( 'LDTP_DEBUG_FILE' , None )
if _ldtp_debug :
    print ( "Parent PID: {}" . format ( int ( parentpid ) ) )
if _ldtp_debug_file :
    with open ( unicode ( _ldtp_debug_file ) , "a" ) as fp :
        fp . write ( "Parent PID: {}" . format ( int ( parentpid ) ) )
server = LDTPServer ( ( '' , port ) , allow_none = True , logRequests = _ldtp_debug , requestHandler = RequestHandler )
server . register_introspection_functions ( )
server . register_multicall_functions ( )
ldtp_inst = core . Core ( )
server . register_instance ( ldtp_inst )
if parentpid :
    thread . start_new_thread ( notifyclient , ( parentpid , ) )
try :
    server . serve_forever ( )
except KeyboardInterrupt :
    pass
except :
    if _ldtp_debug :
        print ( traceback . format_exc ( ) )
    if _ldtp_debug_file :
        with open ( _ldtp_debug_file , "a" ) as fp :
            fp . write ( traceback . format_exc ( ) )


signature:
def server_bind ( self , * args , ** kwargs ) :
    '''Server Bind . Forces reuse of port .'''

implementation:
self . socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )
# Can ' t use super ( ) here since SimpleXMLRPCServer is an old - style class
SimpleXMLRPCServer . server_bind ( self , * args , ** kwargs )


signature:
def log ( self , message , level = logging . DEBUG ) :
    """Logs the message in the root logger with the log level
 @ param message : Message to be logged
 @ type message : string
 @ param level : Log level , defaul DEBUG
 @ type level : integer
 @ return : 1 on success and 0 on error
 @ rtype : integer"""

implementation:
if _ldtp_debug :
    print ( message )
self . logger . log ( level , str ( message ) )
return 1


signature:
def stoplog ( self ) :
    """Stop logging .
 @ return : 1 on success and 0 on error
 @ rtype : integer"""

implementation:
if self . _file_logger :
    self . logger . removeHandler ( _file_logger )
    self . _file_logger = None
return 1


signature:
def imagecapture ( self , window_name = None , out_file = None , x = 0 , y = 0 , width = None , height = None ) :
    """Captures screenshot of the whole desktop or given window
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param x : x co - ordinate value
 @ type x : integer
 @ param y : y co - ordinate value
 @ type y : integer
 @ param width : width co - ordinate value
 @ type width : integer
 @ param height : height co - ordinate value
 @ type height : integer
 @ return : screenshot filename
 @ rtype : string"""

implementation:
if not out_file :
    out_file = tempfile . mktemp ( '.png' , 'ldtp_' )
else :
    out_file = os . path . expanduser ( out_file )
# # # Windows compatibility
if _ldtp_windows_env :
    if width == None :
        width = - 1
    if height == None :
        height = - 1
    if window_name == None :
        window_name = ''
# # # Windows compatibility - End
data = self . _remote_imagecapture ( window_name , x , y , width , height )
f = open ( out_file , 'wb' )
f . write ( b64decode ( data ) )
f . close ( )
return out_file


signature:
def onwindowcreate ( self , window_name , fn_name , * args ) :
    """On window create , call the function with given arguments
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param fn _ name : Callback function
 @ type fn _ name : function
 @ param * args : arguments to be passed to the callback function
 @ type * args : var args
 @ return : 1 if registration was successful , 0 if not .
 @ rtype : integer"""

implementation:
self . _pollEvents . _callback [ window_name ] = [ "onwindowcreate" , fn_name , args ]
return self . _remote_onwindowcreate ( window_name )


signature:
def registerevent ( self , event_name , fn_name , * args ) :
    """Register at - spi event
 @ param event _ name : Event name in at - spi format .
 @ type event _ name : string
 @ param fn _ name : Callback function
 @ type fn _ name : function
 @ param * args : arguments to be passed to the callback function
 @ type * args : var args
 @ return : 1 if registration was successful , 0 if not .
 @ rtype : integer"""

implementation:
if not isinstance ( event_name , str ) :
    raise ValueError ( "event_name should be string" )
self . _pollEvents . _callback [ event_name ] = [ event_name , fn_name , args ]
return self . _remote_registerevent ( event_name )


signature:
def deregisterevent ( self , event_name ) :
    """Remove callback of registered event
 @ param event _ name : Event name in at - spi format .
 @ type event _ name : string
 @ return : 1 if registration was successful , 0 if not .
 @ rtype : integer"""

implementation:
if event_name in self . _pollEvents . _callback :
    del self . _pollEvents . _callback [ event_name ]
return self . _remote_deregisterevent ( event_name )


signature:
def registerkbevent ( self , keys , modifiers , fn_name , * args ) :
    """Register keystroke events
 @ param keys : key to listen
 @ type keys : string
 @ param modifiers : control / alt combination using gtk MODIFIERS
 @ type modifiers : int
 @ param fn _ name : Callback function
 @ type fn _ name : function
 @ param * args : arguments to be passed to the callback function
 @ type * args : var args
 @ return : 1 if registration was successful , 0 if not .
 @ rtype : integer"""

implementation:
event_name = "kbevent%s%s" % ( keys , modifiers )
self . _pollEvents . _callback [ event_name ] = [ event_name , fn_name , args ]
return self . _remote_registerkbevent ( keys , modifiers )


signature:
def deregisterkbevent ( self , keys , modifiers ) :
    """Remove callback of registered event
 @ param keys : key to listen
 @ type keys : string
 @ param modifiers : control / alt combination using gtk MODIFIERS
 @ type modifiers : int
 @ return : 1 if registration was successful , 0 if not .
 @ rtype : integer"""

implementation:
event_name = "kbevent%s%s" % ( keys , modifiers )
if event_name in _pollEvents . _callback :
    del _pollEvents . _callback [ event_name ]
return self . _remote_deregisterkbevent ( keys , modifiers )


signature:
def windowuptime ( self , window_name ) :
    """Get window uptime
 @ param window _ name : Window name to look for , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ return : " starttime , endtime " as datetime python object"""

implementation:
tmp_time = self . _remote_windowuptime ( window_name )
if tmp_time :
    tmp_time = tmp_time . split ( '-' )
    start_time = tmp_time [ 0 ] . split ( ' ' )
    end_time = tmp_time [ 1 ] . split ( ' ' )
    _start_time = datetime . datetime ( int ( start_time [ 0 ] ) , int ( start_time [ 1 ] ) , int ( start_time [ 2 ] ) , int ( start_time [ 3 ] ) , int ( start_time [ 4 ] ) , int ( start_time [ 5 ] ) )
    _end_time = datetime . datetime ( int ( end_time [ 0 ] ) , int ( end_time [ 1 ] ) , int ( end_time [ 2 ] ) , int ( end_time [ 3 ] ) , int ( end_time [ 4 ] ) , int ( end_time [ 5 ] ) )
    return _start_time , _end_time
return None


signature:
def verifyscrollbarvertical ( self , window_name , object_name ) :
    """Verify scrollbar is vertical
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name )
    if object_handle . AXOrientation == "AXVerticalOrientation" :
        return 1
except :
    pass
return 0


signature:
def verifyscrollbarhorizontal ( self , window_name , object_name ) :
    """Verify scrollbar is horizontal
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
try :
    object_handle = self . _get_object_handle ( window_name , object_name )
    if object_handle . AXOrientation == "AXHorizontalOrientation" :
        return 1
except :
    pass
return 0


signature:
def setmax ( self , window_name , object_name ) :
    """Set max value
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
object_handle . AXValue = 1
return 1


signature:
def setmin ( self , window_name , object_name ) :
    """Set min value
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
object_handle = self . _get_object_handle ( window_name , object_name )
object_handle . AXValue = 0
return 1


signature:
def scrollup ( self , window_name , object_name ) :
    """Scroll up
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
if not self . verifyscrollbarvertical ( window_name , object_name ) :
    raise LdtpServerException ( 'Object not vertical scrollbar' )
return self . setmin ( window_name , object_name )


signature:
def scrolldown ( self , window_name , object_name ) :
    """Scroll down
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
if not self . verifyscrollbarvertical ( window_name , object_name ) :
    raise LdtpServerException ( 'Object not vertical scrollbar' )
return self . setmax ( window_name , object_name )


signature:
def scrollleft ( self , window_name , object_name ) :
    """Scroll left
 @ param window _ name : Window name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type window _ name : string
 @ param object _ name : Object name to type in , either full name ,
 LDTP ' s name convention , or a Unix glob .
 @ type object _ name : string
 @ return : 1 on success .
 @ rtype : integer"""

implementation:
if not self . verifyscrollbarhorizontal ( window_name , object_name ) :
    raise LdtpServerException ( 'Object not horizontal scrollbar' )
return self . setmin ( window_name , object_name )